What happens if a method throws an exception that was not specified in the method declaration with “throws”

前端 未结 6 1297
忘掉有多难
忘掉有多难 2021-01-01 11:27

I\'ve never used the \"throws\" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I\'ve been u

6条回答
  •  迷失自我
    2021-01-01 12:12

    1. You need to declare checked exceptions that your method throws.
    2. If you declare 'throws Exception' that pretty much covers most if not all checked exceptions
    3. You can always throw an unchecked runtime exception and not have to declare.

    Im pretty sure if you try to throw a checked exception, and haven't declared the method as throwing that type, the code wont even compile (checking now).

    EDIT, right so if you try something simple like

    public static void main(String[] args) {
       throw new Exception("bad");
    }
    

    you get a compile error.

    Specifically for your question, if you invoke a method that is declared to throw Exception(s) you must either try/catch the method invocation, or declare that your method throws the exceptions.

提交回复
热议问题