![]() ![]() If an exception occurs, the program jumps to the catch block. The finally block always executes whether an exception occurs in the try block or not. In the try-catch statement, you place the code that may cause an exception in the try block.Use the C# block to handle exceptions and clean up the resources.However, it ends immediately as long as it reaches the end of the finally block. The program also executes the finally block. In this example, the program returns the result variable in the try block. The following illustrates the control flow of the program when using a return statement inside the try block:Ĭonsole.WriteLine( "Execute the finally block.") Ĭonsole.WriteLine(Test()) Code language: PHP ( php )ġ00 Code language: JavaScript ( javascript ) Create a PHP file with the following script to know the use of try, catch and finally. In the catchblock, you can place the code that handles the exception. Example-3: Handling file error by using try, catch and finally block. ![]() When an exception occurs in the try block, the execution jumps to the catch block. 2) Using the C# try…catch…finally statement with the return statement The trycatch statement allows you to handle exceptions. In this example, the finally block closes the stream reader whether an exception occurs inside the try block or not. close the file if (reader != null) reader.Close() Reader = new "C:\csharptutorial\test.txt") Ĭonsole.WriteLine($ "Error: ") It uses the statement to handle exceptions: StreamReader? reader = null The following program reads a text file line by line and displays the file contents to the console. 1) Using the C# try…catch…finally statement example Let’s take some examples of using the statment. In practice, you often use the finally block to clean up the resources such as closing a stream or a database connection. ![]() Otherwise, the program will fail to compile. It’s important to note that even if the try clause has a return statement, the finally block will always execute.Īlso, the finally block cannot contain a return statement. If an exception occurs inside the try block, the appropriate catch clauses are executed followed by the execution of the finally block.If no exception occurs inside the try block, the control skips over any catch block and goes to the finally block.When a try.catch statement contains a finally, it always executes the finally block whether an exception occurs inside the try block or not: The try.catch statement has an optional finally clause as follows: try Introduction to the C# try…catch…finally statement Summary: in this tutorial, you’ll learn how to use the C# statement to handle exceptions and clean up resources. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |