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

前端 未结 6 1339
忘掉有多难
忘掉有多难 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:29

    Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.

    Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All other exceptions have to be handled in the method body, either with a try/catch statement or with a throws declaration.

    Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.

    Example for checked exceptions: IOException that some methods from the java.io package might throw. Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to the method caller.

提交回复
热议问题