Which is the correct way to handle an exception?

Which is the correct way to handle an exception?

Usual way of error handling is this : if you can solve the problem locally, then use if statement (or if the function throw an exception, handle that exception) if you can not solve the problem locally, then throw an exception (or if the function throw an exception, let it propagate further), and handle it where you know what to do about it

When is it bad practice to throw exceptions?

If you pass a null parameter to a method that requires that parameter to not be null, you will get an ArgumentNullException, and it is usually bad practice to throw any other exception or to assume some base case that equates null with a discrete value.

When to use exceptions in a C + + program?

I’ve used exceptions for their information carrying ability. In C++, a function return code is usually a single value. In contrast, you can throw exceptions of any class type containing any information that you want. I used an exception to return the specific piece of a query that was not found.

When to use an exception in a function?

In contrast, you can throw exceptions of any class type containing any information that you want. I used an exception to return the specific piece of a query that was not found. It seemed the lesser evil than to add a mostly unused pointer or reference to each function call in a 7-deep call stack.

When to use a try / catch block instead of a statement?

You should usually only catch an exception if you can actually handle it – which is relatively rare. In particular, just swallowing an exception is almost always the wrong thing to do. I write far more try/finally blocks (effectively – almost always via using statements) than try/catch blocks.

Is there a way to catch the same argumentnullexception?

And, you can catch that same ArgumentNullException thrown from any method that cares whether one of its passed parameters was null, instead of having to know that this method would return -2 and another method returns -3 in the same situation. By that token, try-catch helps to standardize the expected behavior in a particular exceptional case.