Exception in Java7 min read

What is an Exception?

  • An exception in Java is a condition that is caused by a program’s run-time error. When the Java interpreter discovers a problem, such as dividing an integer by zero, it constructs and throws an exception object.
  • In other words, an exception in Java can be defined as a problem that arises during the execution of a program. When an exception occurs, the program’s usual flow is broken, and the program/application terminates unexpectedly, which is not desirable. As a result, these exceptions must be handled.
  • If the exception object is not caught and handled properly, the interpreter display an error message and will terminate the program. If we want the program to keep running after the error condition, we should try to capture the exception object thrown by the error condition and then display an appropriate message with instructions on how to fix it. This task is known as exception handling.
  • The exception handling mechanism’s goal is to detect and report “exceptional circumstances” so that appropriate action can be done.

The mechanism suggests the incorporation of a separate error handling code that performs the following tasks:

  1. Find the Problem(Hit the exception)
  2. Inform that an error has occurred (throw the exception)
  3. Receive the error information (catch the exception)
  4. Take corrective action (handle the exception)

The error handling code is divided into two sections, one for detecting mistakes and throwing exceptions, and the other for catching exceptions and taking relevant actions.

Some of these exceptions are caused by user error, some by programmer error, and others by physical resources that have failed in some manner. For example:

  • Invalid data was entered by a user.
  • There is no way to open a file that needs to be opened.
  • The JVM has run out of memory or a network connection has been lost in the middle of conversation.

An exception can occur for many different reasons, below given are some scenarios where an exception occurs.

Three types of Exceptions

  1. Checked exceptions: A checked exception is a type of exception that occurs as a result of a user error or a situation that the programmer could not anticipate. An exception arises, for example, when a file is to be opened but the file cannot be found. These exceptions cannot be simply ignored throughout the compilation process.
  2. Runtime exceptions: A runtime exception is an exception that happens during execution that the programmer might have avoided. Runtime exceptions, in contrast to checked exceptions, are ignored during compilation.
  3. Errors: These aren’t exceptions at all, but rather issues that are beyond the user’s or programmer’s control. Because you can rarely do something about an error, errors are usually disregarded in your code. If a stack overflow happens, for example, an error will ensue. They are also overlooked throughout the compilation process.

Common java exceptions

Exception TypeCause of Exception
ArithmeticExceptionCaused by math errors such as division by zero.
ArrayIndexOutOfBoundsExceptionCaused by a bad array index.
ArrayStoreExceptionCaused by when a program tries to store the wrong type of data in an array.
FileNotFoundExceptionCaused by an attempt to access a nonexistent file.
IOExceptionCaused by general I/O failures, such as inability to read from a file.
NullPointerExceptionCaused by referencing a null object.
NumberFormatExceptionCaused when a conversion between strings and number fails.
OutOfMemoryExceptionCaused when there’s not enough memory to allocate
SecurityExceptionCaused when an applet tries to perform an action not allowed by the browser’s security setting.
StackOverFlowExceptionCaused when the system runs out of stack space.
StringIndexOutOfBoundsExceptionsCaused when a program attempts to access a nonexistent character position in a string.
Common Java Exceptions

Syntax of Exception Handling

try {
} catch(ExceptionType e) {


public class JavaExceptionExample {  
  public static void main(String[] args) {
    try {  
      //code that may raise exception  
      int data = 100 / 0;  
    } catch(ArithmeticException e) {
    //rest code of the program   
    System.out.println("rest of the code...");  


Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Multiple Catch Statements

A single piece of code could trigger several exceptions in some instances. You can define two or more catch clauses to address this issue, each catching a distinct type of exception. When an exception is thrown, each catch statement is examined one by one, and the first one that matches the exception’s type is performed. The others are skipped once the first catch statement executes, and the exception continues after the try/catch block.

Exception classes

  • In Java, exceptions are objects. You throw an object when you throw an exception. You can’t throw just any object as an exception, however, only those objects whose classes descend from Throwable.
  • Throwable is the basic class for a whole family of java.lang classes that your program can use to instantiate and toss.
Hierarchy of Java Exception classes


  • Consider the following scenario: you’re creating Java software that replicates a virtual café customer drinking a cup of coffee. Consider any unusual circumstances that may arise while the customer is sipping.
  • The class hierarchy of exceptions is shown in the following figure which represents a few possibilities.
Exception hierarchy for coffee sipping


  • An exception can In exception handling we may require to throw an exception explicitly. This is done by using either throw or throws clause be thrown either by the system or by a statement.
  • The program can throw an exception in the hope that some other part of the program will catch and handle the exception.
  • When throwing statement encounters, execution stops immediately and it inspects for the nearest catch statements that match the type of exception.
  • If no matching catch is found, the default exception handler halts the program and prints the stack trace To throw an exception, a throw statement is used.
  • Its syntax is Throw exception-object; Exception-object must be an object belonging to any one of the subclasses of exception.
  • We can also create an exception object using the constructor and a new operator, for eg. Throw new ArithmeticException(“Division by zero.”); The argument of the constructor must be an error message in the exception object.

Throws and finally


  • If any exception occurs in a method but is not handled then this should specify to the caller of the method so that it can guard them against that exception.
  • A throws clause in the method’s declaration does this job.
  • A throws clause lists the types of exceptions that a method might throw. If any exception is not listed then a compile-time error occurs.

The general form of the throws clause is

returnType methodName(argument_list) throws exception-list { 
  //method body 

The exception in the exception list must be comment separated.


  • After handling the exception, the computer executes The finally clause of the try statement (if finally clause is specified) and then continues normally the rest of the program.
  • finally block is executed after the try/catch block has been completed but before the code follows the try/catch block.
  • If an exception is thrown but no catch matches the exception type then finally will execute it.
  • Although the final clause is optional, each or a final clause. The following example describes how finally works in different situations.

Creating New Exception

  • Java provides several in-built exceptions but they handle the most common errors. In some situations, we programmers may require to define new exceptions.
  • By extending the Exception class we can create our new exception.
  • The Exception class does not define any method but inherited methods provided by Throwable. And hence all these methods are available to newly created exceptions also.

Some methods defined by Throwable are tabulated below :

String getMessage()Returns description of the exception.
String toString()Returns a string object containing a description of the exception. This method is called println when outputting a Throwable object.
void printStackTrace()Displays the stacktrace.
Throwable getCause()Returns the cause of this throwable or null is cause does not exist or unknown.
void printStackTrace (printWriter s)Prints the stack trace to the specified printWriter.


Leave a Reply