What is the use of specifying exceptions in Java?

I came to Java from C ++. In both Java and C ++, we have the ability to specify exceptions. It looks like this:

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

      

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

What is the use of writing exception specifications in Java?

+3


source to share


2 answers


You should only specify checked exceptions (class subclasses Exception

) in the method signature. Unchecked exceptions (class subclasses RuntimeException

) do not need to be specified.

Throwing exceptions in a method signature is an essential Java practice, defined by the semantics of the language. But there is also a lot of controversy about this. Some teams and projects even consider this to be bad practice and only use unchecked exceptions.



Generally, as a good practice, you should throw a checked exception when you define it as part of a method contract, that is, the caller must know some specific (quite possible and recoverable) error type and either catch and handle it or pass it call stack. Unchecked exceptions usually mean some kind of internal error in the method's code and therefore don't need to be caught.

+4


source


There is no profit in Java, exception specification is required. Java was designed with a stronger type system than C ++. In C ++, the exception specification was optional, and the Java developers believed that an exception was an important part of program design, so they decided to apply the exception specification whenever a function could throw anything. It is sometimes controversial, but this is a choice of language. The exception is part of the call contracts.



0


source







All Articles