I am wondering can try..catch
force execution to go into the catch
and run code in there?
here example code:
try { if (AnyConditionTrue) { // run some code } else { // go catch } } catch (Exception) { // run some code here... }
No, multiple catch blocks cannot be executed. Once first catch block is catched, it will not read the next block.
To resolve this you need to either wrap the calling line or throw the exception again using the throws keyword. That being said, if you handle the exception using try-catch pair in the source method (the method that generates the exception originally) there is no need to handle it again in the calling method.
A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.
Rather than throwing an Exception in the else
, I would recommend extracting the code from your catch
into a method and call that from your else
try { if (AnyConditionTrue) { MethodWhenTrue(); } else { HandleError(); } } catch(Exception ex) { HandleError(); }
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