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?
-
Professors are always right, believe them. If any doubt catch them post-class and they would be happy to oblige you.hagrawal7777– hagrawal77772015-10-11 02:05:17 +00:00Commented Oct 11, 2015 at 2:05
-
How to define custom exception class in JavaGabrielOshiro– GabrielOshiro2015-10-11 02:07:26 +00:00Commented Oct 11, 2015 at 2:07
3 Answers
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?
You can catch exceptions of specific types.
try { ... } catch(ExceptionType1 e) { ... } catch(ExceptionType2 e) { ... }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 { ... }
1 Comment
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.
2 Comments
Exception catch block, use specific exception catch block, so truly answer is too broad and opinion based.