Is it a good design practice to code a try-catch
block as follows? That is, use a throw
in the try block and then catch it in the catch block.
try
{
if (someCondition){
throw new Exception("Go the the associated catch block!");
}
}
catch(Exception ex)
{
logError("I was thrown in the try block above");
}
(For exceptions) Be careful of how much code you put in your try blocks. It's considered best practice to put as little code as possible in each try / catch block. This means that you may need multiple try / catch blocks, instead of just one.
The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.
Explanation: The statements which may cause problems are put in try block. Also, the statements which should not be executed after a problem accursed, are put in try block. Note that once an exception is caught, the control goes to the next line after the catch block.
The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.
Exceptions are for exceptional circumstances. It should not be used as control of flow logic but if there is a edge case that needs to be handled if it does come up there is nothing wrong in doing it.
I have done this myself throwing a InvalidDataException in my code if the data I am reading is not what I am expecting.
In general, it is not bad design, if it is the shortest writable method. But beware, that throwing an excaption usually takes approximetaly 1 ms to catch. In that matter it is a performance issue.
There are times when you might want to - for example, if you're using ado.net, it has a habit of throwing everything as a SqlException
- you might want to catch some of these, and handle them, whilst leaving the handling of others to another level. In this case, you'd have to catch the SqlException, see if you can handle it, and rethrow it if not.
It depends, you should throw exception in an usual situation and is better your own exception rather than a general one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With