Control Flow

Try Catch Block in C#

A try-catch block is used to mitigate errors in code and prevent program crashing during runtime. It 'tries' a block of code that could give an error. If the error (exception) is caught, it will execute a different block of code rather than crash the program.


Syntax
try {
    //code to try, that may throw an exception
}
catch (ExceptionType ExceptionName) {
    //code to be run if exception is caught
}
finally {
    //code to execute regardless of whether or not exception is caught
}

Notes

The exception name is an arbitrary name, similar to declaring a variable.

Exception types can either be built into Java, within a standard library, or written by the user.

A try catch block can catch multiple types of exceptions. To do so, include multiple catch blocks.

The finally block is always executed when the try-catch block is entered.


Example
try {
    int[] array = new int[3];
    array[7] = 3; //code that will throw an exception, array index out of bounds
}
catch (IndexOutOfRangeException e) {
    //runs this instead of crashing the program
    Console.WriteLine("Array index is out of bounds!"); 
}
finally {
    Console.WriteLine("The array is of size " + array.length);
}

See Also
Documentation

try-catch (C# Reference) - MSDN

Add to Slack

< Do While Loop   |   Class Declaration and Structure >

© 2019 SyntaxDB. All Rights Reserved.