Exception handling is common to most programming languages, and the mechanism and behaviors are similar in most languages: try\catch\finally. It is well documented. We are not going to discuss that.

However, different approach to exception handling is required in different types of applications like a Library, a UI application, a Framework, etc., and that is the focus of this article. We’ll see how exception handling needs to change depending on the nature of the application.

Let’s start with some fundamentals.

What is an exception?

Exception is an event during the execution of a program that disrupts the normal flow and prevents the program from doing what it is expected to doe.g., a program tries to write to a log file but the file cannot be opened.

In such error conditions, runtime looks for handlers (try-catch) that are registered to handle such exceptions, and when a handler is found, it is invoked with an Exception object having information about the event. The following diagram shows the normal flow of the program (Runtime > main > Method1 > Method2) and the flow when an exception occurs in Method2.

When an exception is not handled by a program, it reaches the runtime where it will be considered an unhandled exception which may result in a crash.

**Two Pass vs One Pass: **Net Runtime has Two Pass exception handling implementation. Two Pass means the runtime first traverses through entire call stack to find a handler, and after either finding a handler or determining that its an unhandled exception, it runs all the finally blocks in the call stack. JVM on the other hand runs finally block in a method if a handler is not found in that method and then it moves up the call stack. See CLR Exception Handling and JVM Exception Handling for detailed explanation.

Asynchronous Execution

Exception handling in asynchronous execution is little different and it is important to understand. Let’s see with an example.

The following is Java code that runs a method on new thread and exits.

public class AsyncRun implements Runnable {
  @Override
  public void run() {
        // TODO Auto-generated method stub
    System.out.println("AsyncRun.run on thread " + Thread.currentThread().getId());
    throw new ArithmeticException();
  }    
}

public static void main( String[] args ) {
  try {
    Thread t = new Thread(new AsyncRun());
    t.start();
    System.out.println( "main on thread " + Thread.currentThread().getId());
    throw new NullPointerException();
  }
  catch(Exception ex)
  {
    System.out.println(ex.getClass().getName() + " handled");
  }
}

#programming #software-engineering #software-architecture #error-handling #code-quality #software-design #java #csharp

Exception Handling with Examples
1.15 GEEK