In Java, you can use a try
block to enclose code that might throw an exception. You can follow the try
block with a catch
block to handle the exception if it is thrown. For example:
try { int[] myArray = new int[5]; myArray[6] = 10; // this line will throw an ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("An ArrayIndexOutOfBoundsException was caught."); }
In this example, the try
block contains code that tries to access an element of an array with an index that is out of bounds. This will cause an ArrayIndexOutOfBoundsException
to be thrown. The catch
block following the try
block catches this exception and prints a message.
You can also use a finally
block after the catch
block to execute code that should be executed regardless of whether an exception is thrown. The finally
block is optional.
try { // code that might throw an exception } catch (ExceptionType e) { // code to handle the exception } finally { // code to be executed regardless of whether an exception is thrown }