Try and Catch and Finally in CSharp
In this tutorial, we’ll use try, catch and finally.
The Try and Catch command encloses a code section and is used to catch possible errors (exceptions) within the code section so that you can react to them.
Example of the general syntax of Try and Catch
try {
// code which is run securly
} catch (ExceptionClassname variablename) {
// Error handling
}
A try-catch statement consists of four parts. The “try” block that runs securely and may throw an exception that we can intercept. We then perform the error handling within the catch block. The exception class name describes the error to which we want to react. We can intercept several exceptions. The variable name names the exception within the catch block so that we can respond to the exception within the catch block. (E.g., InputOutputException – if the connection to the Internet did not work).
If the caught exception is thrown within the try block, our program jumps directly into the catch block. If the exception is not thrown, the catch block is not called and our code continues as normal.
Example of Try & Catch and Finally in CSharp
public class Panjutorials { public static void Main(string[] args) { Console.WriteLine("How old are you?"); string input = Console.ReadLine(); try { int age = Int32.Parse(input); Console.WriteLine("You are " + age + " years old."); } catch (Exception e) { Console.WriteLine("You didn't enter a number."); } Console.ReadLine(); } }
So here we use a user input. We show him the text “How old are you?”. Since we expect as input a value which we can convert into an integer, but the input can also be something other than a number, we surround the conversion with a try and catch. So we try to convert the input, if this does not work, the catch block should be executed.
It is important that we use Try and Catch, otherwise our program would crash if the input of the user can not be converted into an integer.
With Try and Catch there is the possibility to add the term Finally. This is used to execute code, no matter whether Try or Catch was carried out, whether the code in the try block has worked, or not.
try {
// code runs securely
} catch (ExceptionClassname variablename) {
// Error handling
} finally {
// will run in any case
}
Finally is extremely useful for e.g. returning a variable to its original state, close the program, or terminate an (Internet) connection.