Compiler Error J0122

Exception 'identifier' not caught or declared by 'identifier'

The compiler detected an exception that was thrown but never caught within the exception class. This error usually occurs when a method calls another method that is declared to throw an exception. In order for a method to call another method that throws an exception, the method must either be declared to throw the exception or handle the error using a try/catch combination.

The following example illustrates this error:

class SimpleException extends Exception {
   // do something meaningful
}

class Simple {
   
   void method1() throws SimpleException { }
   void method2() { method1(); } 
   // error: exception not declared for method2
}

The following examples illustrates how to call a method that is declared to throw an exception:

/*This example illustrates handling by declaring the other method as
throwing an exception duplicate to the method it is calling.*/
class SimpleException extends Exception{
   //do something here
}

public class Simple{
   void method1() throws SimpleException{
      //do something here
   }
   void method2() throws SimpleException{
      method1(); //caller of method2 now is forced to handle exception
   }
}

/*This example illustrates handling the exception using a try/catch
  combination.*/
class SimpleException extends Exception{
   //do something here
}

public class Simple{
   void method1() throws SimpleException{
      //do something here
   }
   void method2(){
      try{
        method1();
      }
      catch(SimpleException e){
         //handle exception here
      }
   }
}