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?

+1


source to share


4 answers


Modify your code to catch all exceptions in one block and determine the type and execution path from there.



+9


source


You can call functions in exception handlers.



Try
'Some code that causes exception'
Catch ex as ExceptionType1
  handler_1()
  handler_2()
  handler_3()
Catch ex as ExceptionType2
  handler_2()
  handler_3()
Catch ex as ExceptionType3
  handler_3()
Finally
  handler_4()    
End Try

      

+3


source


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.

+2


source


I think you could get the behavior you want if you nested try blocks. When an exception is thrown, execution jumps to the catch block. If nothing is reborn, it goes to the final.

+1


source







All Articles