![]() ![]() Check for null because OpenWrite might have failed.įor more information, see Exceptions and The try statement in the C# Language Specification. FileStream? file = null įileInfo fileinfo = new System.IO.FileInfo("./file.txt") Instead, if the file is opened successfully in the try block, the finally block closes the open file. If the try block can't open the file, the file handle still has the value null and the finally block doesn't try to close it. Notice that the state of the file handle is checked before the file is closed. In the following example, the finally block is used to close a file that is opened in the try block. ![]() For more information See the using Statement. The finally block can be used to release resources such as file streams, database connections, and graphics handles without waiting for the garbage collector in the runtime to finalize the objects. A finally block always runs, whether an exception is thrown or a catch block matching the exception type is found. ![]() If present, the finally block executes last, after the try block and any matched catch block. Finally BlocksĪ finally block enables you to clean up actions that are performed in a try block. The catch clause can be general, using System.Exception, and later clauses can process more specific exception classes. The LogException method always returns false, no catch clause using this exception filter matches. Private static bool LogException(Exception e)Ĭonsole.WriteLine($"\tIn the log routine. A typical use is to log exceptions: public static void Main()Ĭatch (Exception e) when (LogException(e))Ĭonsole.WriteLine("Exception must have been handled") "Parameter index cannot be greater than the array size.", e) Īn exception filter that always returns false can be used to examine all exceptions but not process them. "Parameter index cannot be negative.", e) In the following example, both catch clauses use the same exception class, but an extra condition is checked to create a different error message: int GetInt(int array, int index)Ĭatch (IndexOutOfRangeException e) when (index < 0) Exception filters indicate that a specific catch clause matches only when that condition is true. You can also specify exception filters to add a boolean expression to a catch clause. Call a custom error logging procedure. In the following example, a catch block is used to add an entry to an error log before rethrowing the exception.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |