2

Which is a better approach to exception handling and why?:

(1) Defining a single exception for the whole application which takes a string message and displays it. Use this exception everywhere with a specific message appropriate to the scenario.

I have no idea why this is not appropriate.

(2) Defining a new exception class for each different case in the application.

I feel this is not appropriate because there are cases where the exception is at just one place in the application. e.g. amount entered is -ve Is it ok to create a whole new exception class just for a single case in the app ?

4 Answers 4

2

Define a new exception for each kind of error that matters to your user. So, for example, ideally you should catch NullPointerException inside your program, and turn it into a CustomerLookupException to that the user level of the program can report "Software error retrieving customer." Exception chaining is handy for this, as you can pass along the original exception as well.

The whole Java Tutorial on exceptions is a good resource.

Sign up to request clarification or add additional context in comments.

Comments

2

Definitely defining new exception for all different cases.

Imagine you are implementing an interpreter/compiler. You gonna have modules as SemanticVerifier, Interpreter, CodeGenerator (and others of course). You want to know what kind of exception gonna be thrown when your program crash. Oh there it's Semantic! there look it's a bug in the Interpreter! And you want the user to know so he can report a more precise bug.

I personally think it leads to a better design if you have separate exceptions for every module.

2 Comments

Can you please elaborate a bit. Why definitely this ?
@NikunjChauhan what i was doing exactly :)
1

You should define a new exception for each case.

The reason is so that each Exception can be handled independently.

For example, catching the Exceptions differently allows you to either continue in some cases, or end in others.

Comments

0

in my view your 1st option is more suitable

(1) Defining a single exception for whole application which takes a string msg and displays it. And using it at all places with appropriate place specific message.

Even i am using a single exception in the application. If you create separate exception for each type it will increase complexity. It will have lot of redundant code. For denoting different type of exception, you can pass a parameter(type or something) in the common exception itself.

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.