Is there something wrong if you throw exceptions in the try block?

Is it a good practice to design try-catch code as follows? That is, use 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"); } 
+6
source share
6 answers

There are times when you want - for example, if you use ado.net, he has the habit of throwing everything like SqlException - you may want to catch some of them and handle them, while leaving other people at a different level. In this case, you will have to catch the SqlException, see if you can handle it, and flip it if not.

+3
source

Exceptions to exclude all circumstances. It should not be used as a control of the flow logic, but if there is a boundary register that needs to be processed, if it appears, there is nothing wrong with that.

I did this myself, throwing an InvalidDataException into my code if the data I read is not what I expect.

+3
source

In general, this is a good design if it is the shortest way to record. But be careful that throwing an intercept usually takes about 1 ms to catch. In this regard, this is a performance issue.

+2
source

It depends, you should throw an exception in a normal situation and your own exception is better, rather than a general one.

+1
source

It totally depends on what you are trying to achieve. In general, it is best to avoid overuse of try-catch blocks, not least because they are slow. Many try-catch blocks can make your code look dirty and hard to follow.

You need to think about why an exception will be thrown, is this an unforeseen error, an error, or an expected error? If its the expected error, you should try to create code around it without using try-catch.

+1
source

If someCondition represents the true error state, then yes. There is no problem with this. However, please do not use it to control program flow. Nothing makes me more nuts than to see an exception that throws when you can just get out of the field. It also has the potential to compromise the proper handling of real exceptions in your code.

+1
source

Source: https://habr.com/ru/post/915714/


All Articles