James Akwuh
James Akwuh

Reputation: 2217

What's the benefit of exceptions specification in Java?

I came to Java from C++. Both in Java and C++ we have the possibility to specificate exceptions. It looks like this:

void function_name() throw(Exception)
{
  ...
  if (error) 
  {
    throw Exception("Error");
  }
  ...
}

As I know, writing exceptions specification is considered to be a bad practice in C++. Unlike C++, in Java we have to do this. So, my question is:

What's the benefit of writing exceptions specification in Java?

Upvotes: 5

Views: 1457

Answers (2)

Forketyfork
Forketyfork

Reputation: 7810

You have to specify only checked exceptions (subclasses of the Exception class) in the method signature. Unchecked exceptions (subclasses of the RuntimeException class) don't need to be specified.

Specifying exceptions in method signature is an inherent Java practice defined by the language semantics. But there is also much controversy about it. Some teams and projects even consider it a bad practice and use only unchecked exceptions.

Generally, as a good practice, you should throw a checked exception when you define it as a part of method's contract, i.e. the method caller has to be aware of some specific (quite possible and recoverable) type of error and either catch and process it, or pass it up the call stack. Unchecked exceptions usually signify some internal error in the code of the method and thus need not be catched.

Upvotes: 5

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36401

There is no profit in Java, exception specification is mandatory. Java was designed with a more strong type system than C++. In C++, exception specification was optional, and Java designers thought that exception is a important part of program design, so they decided to enforce exception specification whenever a function may throw any. This is sometimes controversial, but is a language design choice. Exception are part of calls contracts.

Upvotes: 0

Related Questions