Exception Handling

Introduction

Exception can be treated as errors or flaws in a program that crop up during run-time. These are unwanted or unexpected events that inhibit the natural flow of a program and result in the program stopping without producing the desired results. However, exceptions are quite different from the literal meaning of errors. Errors can be logical or syntactical. In such cases, although your program will run, you might not end up getting the result that you had expected. It is a problem that an application should not try to catch. On the other hand, exceptions should be caught by typical applications. In this article we will discuss Exception Handling in Java.

Exception Hierarchy

The Exception Hierarchy states that all errors and exceptions are part of the Throwable class. This class is then subdivided into two parts. One part is headed by Exceptions while the other is headed by Error. Both checked as well as unchecked exceptions are part of the Exceptions branch. An example of this is NullPointerException. The Error branch is mainly used by the JVM (Java Virtual Machine) to point out errors in the run-time environment. The StackOverFlow error is part of this branch.

How does the JVM handle an Exception?

When an exception occurs inside a method, an Exception Object is created immediately and handed over to the Java Virtual Machine. All the details of the exception including the name and the state of the program when the exception took place will be contained inside the Object. This process of object creation and passing it to the JVM is known as throwing an Exception. Thereafter, the JVM calls the Exception Handler to deal with the object. The handler searches through the Call Stack and calls the appropriate method which will be able to handle the exception. Thereafter, details of the problem is printed out. If no method is found in the Call Stack, the default exception handler is called.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.