Exception is never thrown in body of corresponding try statement

后端 未结 4 1724
别那么骄傲
别那么骄傲 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.

提交回复
热议问题