2

In Java in a Nutshell, it says that we must declare the checked exceptions that a method can throw, by throws.

I was wondering if we must declare any unchecked exception that a method can throw, by throws or other ways?

Does the answer depend on whether the unchecked exception is predefined or self-defined?

Thanks.

  • "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. – Andrew Tobilko Nov 21 '17 at 20:40

4 Answers4

2

You can declare unchecked exceptions but you don't have to. It does not matter if an unchecked exception is built-in or one that you wrote yourself.

Robin-Hoodie
  • 4,886
  • 4
  • 30
  • 63
1

No, you do not need to declare unchecked exception in throws.

It may be helpful to future developers using your function - including your future self - to declare which unchecked exceptions may be thrown in a javadoc segment, like:

/**
 * @throws {@link MyUncheckedException} whenever blah blah case occurs
 */
Jacob Davis-Hansson
  • 2,603
  • 20
  • 26
1

You can but never need to declare unchecked exceptions, whether you declare them yourself or not.

Exceptions inheriting from RuntimeException are unchecked.

daniu
  • 14,137
  • 4
  • 32
  • 53
0

Unchecked exceptions are run time exceptions. So it means that even if you don’t use throw, it’ll compile and run. Like ArithmeticException is an unchecked exception, but even if you don’t use throw the program will compile and run till someone uses a value which throws that exception.

So in a line, no it is not COMPULSORY to use throw in an unchecked exception.

Neeraj Yadav
  • 422
  • 6
  • 13