Exception is never thrown in body of corresponding try statement

后端 未结 4 1712
别那么骄傲
别那么骄傲 2020-12-03 05:14

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\");. T

相关标签:
4条回答
  • 2020-12-03 05:33

    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.

    0 讨论(0)
  • 2020-12-03 05:33

    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

    0 讨论(0)
  • 2020-12-03 05:42

    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.

    0 讨论(0)
  • 2020-12-03 05:43

    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.

    0 讨论(0)
提交回复
热议问题