Exceptions


When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).

Try and Catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed if an error occurs in the try block. The try and catch keywords come in pairs:
try {
  //  Block of code to try
}
catch( Exception e ) {
  //  Block of code to handle errors
}

The following example will generate an error during execution, because myNumbers[10] does not exist.

NoTryBlock.java (without a try block)
public class NoTryBlock {
  public static void main( String[ ] args ) {
    int[ ] myNumbers = { 1, 2, 3 };
    System.out.println( myNumbers[10] );
  }
}
shell> java NoTryBlock          

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:

TryBlock.java (with a try block)
public class TryBlock {
  public static void main( String[ ] args ) {
    try {
      int[ ] myNumbers = { 1, 2, 3 };
      System.out.println( myNumbers[10] );
    }
    catch ( Exception e ) {
      System.out.print( "Out of bound" );
      e.printStackTrace( );
    }
  }
}
shell> java TryBlock          




      “The measure of intelligence is the ability to change.”    
      ― Albert Einstein