Try Catch block
I have the following code
Try
'Some code that causes exception
Catch ex as ExceptionType1
'Handle Section - 1
Catch ex as ExceptionType2
'Handle section - 2
Catch ex as ExceptionType3
'Handle section - 3
Finally
' Clean up
End Try
Suppose ExceptionType1 is called by code that is processed by section - 1. After processing this section in section 1, can control be passed to section-2 / section-3? Is it possible?
source to share
You did not specify the language and I donβt know the language, so I answer in general.
You cannot do this. If you want to have generic code, place it either in finally
, or if you only need to execute it for some hooks, you can copy that code where appropriate. If the code is larger and you want to avoid redundancy, you can put it in your own function. If that makes your code less readable, you can nest try / catch blocks (at least in Java and C ++. I don't know your language). Here's an example in Java:
class ThrowingException {
public static void main(String... args) {
try {
try {
throw new RuntimeException();
} catch(RuntimeException e) {
System.out.println("Hi 1, handling RuntimeException..");
throw e;
} finally {
System.out.println("finally 1");
}
} catch(Exception e) {
System.out.println("Hi 2, handling Exception..");
} finally {
System.out.println("finally 2");
}
}
}
This will print:
Hi 1, handling RuntimeException..
finally 1
Hi 2, handling Exception..
finally 2
put your generic code in an outer catch block. Doing this with the nested version also handles cases where the exception occurs without explicitly re-throwing the old one in the catch block. This might match what you want even better, but it might not be the case either.
source to share