35

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?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user3407967
  • 523
  • 1
  • 5
  • 11

4 Answers4

42

A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).

try {
    //do something that throws ExceptionA, e.g.
    throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
    //do something to handle the exception, e.g.
    System.out.println("Message: " + e.getMessage());
}

What you are trying to do is this:

try {
    throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
    System.out.println("Message: " + e.getMessage());
}

This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.

Christian
  • 1,589
  • 1
  • 18
  • 36
  • According to your explanation this code should also throw error but it compiles fine. Can you please explain why ? import java.io.*; class a { public static void main(String [] args) { try { new a().go(); } catch(Exception e) { System.out.println("error"); } } void go() {} } – Aman Apr 21 '15 at 14:45
  • I have no IDE at my hands right now, but I would assume that since ´Exception` is the super-class of checked and unchecked exceptions, it will compile. E.g., a Nullpointer-Exception (which is an unchecked exception and a subclass of Exception) could basically be thrown anywhere, thus the code would compile... – Christian Apr 21 '15 at 14:51
  • Your snipped is amazing - yes, that's exactly what I want to write! To be precise, my `ExceptionA` is `InterruptedException` which obviously never written in the code, but being raised from other thread. How can I `catch InterruptedException`? – The Godfather Nov 11 '18 at 10:22
  • 1
    @TheGodfather: I think this one here answers your question -> https://stackoverflow.com/questions/6546193/how-to-catch-an-exception-from-a-thread – Christian Nov 12 '18 at 12:04
9

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.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • Ok, now it works, but i still don't get the messege i want to get from that exception ( Bledne dane ), now I get normal exception messege ( Exception at thread "main" java.lang... – user3407967 Mar 24 '14 at 15:27
  • @user3407967 Can you post your entire exception message? – Duncan Jones Mar 24 '14 at 15:29
  • E:\workspace\pascal1\src\pascal1>java Test 8 a Exception in thread "main" java.lang.NumberFormatException: For input string: "a " at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at Test.main(Test.java:14) – user3407967 Mar 24 '14 at 15:31
  • @user3407967 That exception is thrown on line 14, which is in your **second** try block. You have to adjust the exception message for that `catch` clause. – Duncan Jones Mar 24 '14 at 15:32
  • What happens is that you throw your MojException inside the catch-block. Since your main-method forwards this exception (`public static void main(String[] args) throws MojException`) this will terminate your application. – Christian Mar 24 '14 at 15:39
  • Sorry, but i don't get what u mean by: adjust the exception message. I can't use any message i want ? – user3407967 Mar 24 '14 at 15:39
  • So what can I do to make the exceptions not terminate my aplication ? – user3407967 Mar 24 '14 at 15:40
  • @user3407967 In your **second** catch block, you have this `throw new MojException(args[i]+" "+e.getMessage());`. It sounds like you wanted `throw new MojException("Bledne dane");`. – Duncan Jones Mar 24 '14 at 15:40
  • 1
    You have to wrap everything in another try-catch-block to make it work. But to be honest, that would be very ugly code. I think you have to get more familiar with the basic concepts of exception handling in the first place! What you are trying here is throwing one exception to throw another one. Usually that is not neccessary and will not lead to good code. – Christian Mar 24 '14 at 15:55
  • "*you cannot catch an exception that's not thrown by the code within your try block.*" - unless you're catching `java.lang.Exception` or its supertype. – Giorgi Tsiklauri Nov 18 '21 at 08:45
2

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

Astha Garg
  • 1,022
  • 7
  • 21
0

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.