Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Force Execution to the Catch Block?

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... } 
like image 208
user983738 Avatar asked Feb 16 '12 13:02

user983738


People also ask

Is it possible to execute catch block?

No, multiple catch blocks cannot be executed. Once first catch block is catched, it will not read the next block.

Can we to override a catch block in Java?

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.

Is catch block always executed?

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.


1 Answers

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(); } 
like image 137
cadrell0 Avatar answered Sep 18 '22 12:09

cadrell0