[java] Exception is never thrown in body of corresponding try statement

I have a problem with exception handling in Java, here's my code. I got compiler error when I try to run this line: throw new MojException("Bledne dane");. The error is:

exception MojException is never thrown in body of corresponding try statement

Here is the code:

public class Test {
  public static void main(String[] args) throws MojException {
    // TODO Auto-generated method stub

    for(int i=1;i<args.length;i++){
      try{
        Integer.parseInt(args[i-1]);
      }
      catch(MojException e){
        throw new MojException("Bledne dane");
      }
      try{
        WierszTrojkataPascala a = new WierszTrojkataPascala(Integer.parseInt(args[0]));
        System.out.println(args[i]+" : "+a.wspolczynnik(Integer.parseInt(args[i])));
      }
      catch(MojException e){
        throw new MojException(args[i]+" "+e.getMessage());
      }
    }
  }
}

And here is a code of MojException:

public class MojException extends Exception{
    MojException(String s){
        super(s);
    }
}

Can anyone help me with this?

This question is related to java exception

The answer is


Any class which extends Exception class will be a user defined Checked exception class where as any class which extends RuntimeException will be Unchecked exception class. as mentioned in User defined exception are checked or unchecked exceptions So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.

Checked exception are the exceptions that are checked at compile time.

Unchecked exception are the exceptions that are not checked at compiled time


Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.


As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

try{
    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
    throw new MojException("Bledne dane");
}

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.