Control Flow
Try Catch Block in Java
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
int[] array = new int[3];
try {
array[7] = 3; //code that will throw an exception, array index out of bounds
}
catch (ArrayIndexOutOfBoundsException e) {
//runs this instead of crashing the program
System.out.println("Array index is out of bounds!");
}
finally {
System.out.println("The array is of size " + array.length);
}