Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of declaring an exception

Tags:

java

If I have a class called Boat, and if I write :

class Boat throws Exception

Inside my class I am using try catch block to catch ArithmeticException for instance. What benefit there is to declare an exception versus not declaring an exception?

like image 276
Stranger Avatar asked Jan 14 '23 16:01

Stranger


1 Answers

  • A class does not throw exceptions. Only methods do.

  • For some exceptions (checked exceptions that may occur in your code and that you do not catch) the compiler forces you to declare them.

  • You never have to declare RuntimeExceptions (such as ArithmeticException), but you can. This serves as documentation.

  • You can declare checked exceptions that your code does not throw. This makes it future-proof if you might later want to throw them, and also allows for subclasses to do such.

  • When declaring exceptions, you can go broad/generic (throws Exception or even throws Throwable), but it is generally better to be more specific. That gives the people using your code a better idea of what to expect. The whole purpose of having these many specific Exception classes is to make it easier to handle exceptions appropriately (and have the compiler enforce the fact that someone at least thought about doing that).

like image 60
Thilo Avatar answered Jan 21 '23 09:01

Thilo