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?

2
  • Professors are always right, believe them. If any doubt catch them post-class and they would be happy to oblige you. Commented Oct 11, 2015 at 2:05
  • How to define custom exception class in Java Commented Oct 11, 2015 at 2:07

3 Answers 3

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 { ... }
    
Sign up to request clarification or add additional context in comments.

1 Comment

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

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.