简体   繁体   中英

Exception Classes in Java

Exception Handling: Direct quote from a professor, "Although the Exception class can be used directly in a program, it is better to use a specific exception class." He did not extend much on it but I am interested in knowing what others think and if he is right, why?

Your professor probably meant that it is better to throw SomeTypeException than to throw Exception with some text message.

Why is it better to use a typed exception?

  1. You can catch exceptions of specific types.

     try { ... } catch(ExceptionType1 e) { ... } catch(ExceptionType2 e) { ... } 
  2. Types of exceptions thrown by a method give valuable information to the programmer about the method.

     void someMethod() throws SQLException, ParserException { ... } 

    is more meaningful than:

     void someMethod() throws Exception { ... } 

What he means is that nothing prevents you from doing throw new Exception( "this happened" ); and throw new Exception( "that happened" );

But it is best practice to do throw new ThisException() and throw new ThatException();

That's because elsewhere you can catch( ThisException e ) and handle it, knowing precisely what happened, without having to catch( Exception e ) and wonder whether it was thrown because "this" happened, or because "that" happened.

I have been in situations where I had to do String s = e.getMessage(); and then try to parse the string to try and make sense out of it, and believe me, it is not fun at all having to do stuff like that.

My two cents:

Exceptions, as any other part of an API, should be as specific as possible . It's the same reason why you should use specific types as String , Integer or Date instead of plain Object s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM