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 Oct 11 '15 at 02:05
-
[How to define custom exception class in Java](http://stackoverflow.com/questions/3776327/how-to-define-custom-exception-class-in-java-the-easiest-way) – GabrielOshiro Oct 11 '15 at 02: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,555
- 2
- 16
- 31
-
That makes it better. He is typically one that says something and will say "don't ask why, just know that it is true," but I cannot help but wonder for a bigger explanation. Thanks! – Mariela Oct 21 '15 at 19:46
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.

- 56,297
- 11
- 110
- 142
-
He could also mean that instead of using a `Exception` `catch` block, use specific exception catch block, so truly answer is too broad and opinion based. – hagrawal7777 Oct 11 '15 at 02:07
-
@hagrawal well, it is true that he might have meant just that, though I doubt it. Anyhow, I think I have covered both cases. I think this is a reasonable question. – Mike Nakis Oct 11 '15 at 02:13
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.

- 8,563
- 2
- 18
- 46