0

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?

Mariela
  • 19
  • 2
  • 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 Answers3

6

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 { ... }
    
Marcin Król
  • 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
4

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.

Mike Nakis
  • 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
1

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 Objects.

Little Santi
  • 8,563
  • 2
  • 18
  • 46