Java Exceptions Tutorial – Exception Handling In Java With Examples

Java Exceptions Tutorial – Exception Handling In Java With Examples from Coding compiler. Here you will learn about exception statement, types of exceptions in Java, exception hierarchy in Java. Learn Now.!

Java Exceptions Tutorial

Let’s start learning about Java exceptions, types of exceptions in Java and Java exception handling.

  1. Java exception
  2. Java exception statement
  3. Java exception types

Exceptions in Java Tutorial For Beginners

An Java exception is an abnormal condition that occurs in a code sequence at runtime. For example, reading a non-existent file.

A Java exception is an object that describes an exception condition and occurs in a piece of code.

Java Exception Keywords

  • Java exception handling is managed through five keywords: try,catch,throw,throwsand finally.
  • Try Block contains program statement exceptions to monitor.
  • If an exception occurs in the block, an exception is thrown.
  • Catch Statement can catch exceptions and handle it in a reasonable way.
  • To manually throw an exception, use the keyword throw.
  • Any method that throws an exception must be throws specified by a clause.
  • Any code that must be executed after the completion of the try block is placed in the finally block.

Java Exceptions Grammar

To handle an exception, we take an exception that might have code in the try … catch statement.

try { 
// block of code to monitor for errors 
} 
catch (ExceptionType1 exOb) { 
// exception handler for ExceptionType1 
}
catch (ExceptionType2 exOb) { 
// exception handler for ExceptionType2 
}

Program statements that may have exceptions are included in the try block. The exception handler is catch encoded using a statement.

Here ExceptionType is the type of exception that occurred.

Java Exceptions Example

Encapsulate the code to be monitored in the try block and the catch clause.

The following program consists of a try block and a catch clause to handle ArithmeticException errors generated by division:

public class Main {
  public static void main(String args[]) {
    int d, a;
    try { // monitor a block of code.
      d = 0;
      a = 42 / d;
      System.out.println("This will not be printed.");
    } catch (ArithmeticException e) { // catch divide-by-zero error
      System.out.println("Division by zero.");
    }
    System.out.println("After catch statement.");
  }
}

Java Exceptions Example – 2

Once an exception is thrown, program control is moved from the try block to the catch block. Execution never returned from the catch to the try block.

The following code handles the exception and continues.

import java.util.Random;

public class Main {
  public static void main(String args[]) {
    int a = 0, b = 0, c = 0;
    Random r = new Random();
    for (int i = 0; i < 32000; i++) {
      try {
        b = r.nextInt();
        c = r.nextInt();
        a = 12345 / (b / c);
      } catch (ArithmeticException e) {
        System.out.println("Division by zero.");
        a = 0; // set a to zero and continue
      }
      System.out.println("a: " + a);
    }
  }
}

Java Tutorial – Java Exception Statement

 

To prevent and handle runtime errors, including the code in the try block for monitoring.

Immediately after the try block, include a catch clause that specifies the type of exception you wish to capture.

Java try catch statement

public class Main {
  public static void main(String args[]) {
    try { // monitor a block of code.
      int d = 0;
      int a = 42 / d;
      System.out.println("This will not be printed.");
    } catch (ArithmeticException e) { // catch divide-by-zero error
      System.out.println("Division by zero.");
    }
    System.out.println("After catch statement.");
  }
}

Multiple catch clauses

You can specify two or more catch clauses, each capturing a different type of exception.

When an exception is thrown, each catch statement is checked in order, and the first one that matches the type of the exception is executed.

After executing a catch statement, bypass other catch statements and continue execution after the try/catch block.

public class Main {
  public static void main(String args[]) {
    try {
      int a = args.length;
      System.out.println("a = " + a);
      int b = 42 / a;
      int c[] = { 1 };
      c[42] = 99;
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index oob: " + e);
    }
    System.out.println("After try/catch blocks.");
  }
}

When you use multiple catch statements, the exception subclasses must precede any of their superclasses.

Nested try statement

Try statements can be nested.

public class Main {
  public static void main(String args[]) {
    try {
      int a = args.length;
      int b = 42 / a;
      System.out.println("a = " + a);
      try { // nested try block
        if (a == 1)
          a = a / (a - a); // division by zero exception
        if (a == 2) {
          int c[] = { 1 };
          c[4] = 9; // an out-of-bounds exception
        }
      } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Array index out-of-bounds: " + e);
      }
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    }
  }
}

Java throw statement

We can throw an exception in an abnormal situation.

Java throw statement explanation

The general form of throw is as follows:

throw ThrowableInstance; 

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

There are two ways to get a Throwable object: use parameters in the catch clause, or create one using the new operator.

The execution flow stops immediately after the throw statement; any subsequent execution does not execute the statement.

How to use Java throw statement?

public class Main {
  static void aMethod() {
    try {
      throw new NullPointerException("demo");
    } catch (NullPointerException e) {
      System.out.println("Caught inside demoproc.");
      throw e; // rethrow the exception
    }
  }

  public static void main(String args[]) {
    try {
      aMethod();
    } catch (NullPointerException e) {
      System.out.println("Recaught: " + e);
    }
  }
}

Java throws statement

If a method wants to throw an exception, it must specify this behaviour.

This is the general form of a method declaration that contains a throws clause:

type method-name(parameter-list) throws exception-list 
{ 
// body of method 
}

The exception-list is a comma-separated list of exceptions that methods can throw.

public class Main {
  static void throwOne() throws IllegalAccessException {
    System.out.println("Inside throwOne.");
    throw new IllegalAccessException("demo");
  }

  public static void main(String args[]) {
    try {
      throwOne();
    } catch (IllegalAccessException e) {
      System.out.println("Caught " + e);
    }
  }
}

Java finally statement

Any code that will be executed, regardless of the try block placed in a finally block.

This is the general form of exception handling blocks:

try { 
// block of code to monitor for errors 
} 
catch (ExceptionType1 exOb) { 
// exception handler for ExceptionType1 
}
catch (ExceptionType2 exOb) { 
// exception handler for ExceptionType2 
}
// ... 
finally { 
// block of code to be executed after try block ends 
}

finally create a code block to execute after the try/ catch block is completed.

Even if there is no catch statement matching the exception, the finally block will execute.

finally Blocks can be used to close file handles and free any other resources. The finally clause is optional.

public class Main {
  // Through an exception out of the method.
  static void methodC() {
    try {
      System.out.println("inside methodC");
      throw new RuntimeException("demo");
    } finally {
      System.out.println("methodC finally");
    }
  }

  // Return from within a try block.
  static void methodB() {
    try {
      System.out.println("inside methodB");
      return;
    } finally {
      System.out.println("methodB finally");
    }
  }

  // Execute a try block normally.
  static void methodA() {
    try {
      System.out.println("inside methodA");
    } finally {
      System.out.println("methodA finally");
    }
  }

  public static void main(String args[]) {
    try {
      methodC();
    } catch (Exception e) {
      System.out.println("Exception caught");
    }
    methodB();
    methodA();
  }
}

Java Tutorial – Types of Exceptions in Java

The following image shows the Java exception types and Java exceptions hierarchy:

Throwable
|
|
+—Exception.
|    |
|    |
|    +— RuntimeException
|
+—Error

Exceptions and their subclasses are used for exception conditions that should be caught by the user program. You can subclass Exception to create your own custom exception type.

Errors define exceptions that are not expected to be caught under normal conditions. The Java Runtime System uses an error to indicate an error in the runtime environment. Stack overflow is an example of such an error.

Uncaught exceptions in Java

This small program includes an expression that intentionally divides by zero:

public class Main {
  public static void main(String args[]) {
    int d = 0;
    int a = 42 / d;
  }
}

Uncaught exceptions in Java example

Here is another version of the previous program that introduces the same error, but in a method separate from main():

public class Main {
  static void subroutine() {
    int d = 0;
    int a = 10 / d;
  }

  public static void main(String args[]) {
    subroutine();
  }
}

The stack trace generated from the default exception handler shows how to display the entire call stack.

Java Exception Handling Example

You can display an exception description message in the println() statement.

For example, the catch block can be written like this:

import java.util.Random;

public class Main {
  public static void main(String args[]) {
    int a = 0, b = 0, c = 0;
    Random r = new Random();
    for (int i = 0; i < 32000; i++) {
      try {
        b = r.nextInt();
        c = r.nextInt();
        a = 12345 / (b / c);
      } catch (ArithmeticException e) {
        System.out.println("Exception: " + e); 
        a = 0; // set a to zero and continue
      }
      System.out.println("a: " + a);
    }
  }
}

Java built-in exceptions

Exceptions that subclass RuntimeException need not be included in the throws list of any method. These are called unchecked anomalies.

The unchecked exceptions defined in java.lang are listed in the following table.

List of Java Exceptions

abnormal meaning
ArithmeticException Arithmetic error, such as dividing by zero.
ArrayIndexOutOfBoundsException The array index is out of bounds.
ArrayStoreException Assigned to an incompatible type of array element.
ClassCastException Invalid cast.
EnumConstantNotPresentException Try using an undefined enumeration value.
IllegalArgumentException An illegal parameter used to call a method.
IllegalMonitorStateException Illegal monitor operations, such as threads waiting to be unlocked.
IllegalStateException The environment or application status is incorrect.
IllegalThreadStateException The requested operation is not compatible with the current thread state.
IndexOutOfBoundsException Some types of indexes are out of bounds.
NegativeArraySizeException An array created with a negative dimension.
NullPointerException The use of invalid references is invalid.
NumberFormatException The conversion from string to number format is invalid.
SecurityException Trying to violate security.
StringIndexOutOfBounds Try to build an index outside the bounds of the string.
TypeNotPresentException No type found.
UnsupportedOperationException Encountered an unsupported operation.

The checked exceptions are listed in the table below.

Java Exceptions List

abnormal meaning
ClassNotFoundException The class was not found.
CloneNotSupportedException Try to clone an object that does not implement the Cloneable interface.
IllegalAccessException Access to the class was denied.
InstantiationException Try to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException The requested field does not exist.
NoSuchMethodException The requested method does not exist.

Java custom exception class

You can Exceptioncreate your own exception classes through defined subclasses.

The class does not define any of its own methods. It inherits Throwable the methods provided.

The following program creates a custom exception type.

class MyException extends Exception {
  private int detail;

  MyException(int a) {
    detail = a;
  }

  public String toString() {
    return "MyException[" + detail + "]";
  }
}

public class Main {
  static void compute(int a) throws MyException {
    System.out.println("Called compute(" + a + ")");
    if (a > 10)
      throw new MyException(a);
    System.out.println("Normal exit");
  }

  public static void main(String args[]) {
    try {
      compute(1);
      compute(20);
    } catch (MyException e) {
      System.out.println("Caught " + e);
    }
  }
}

Java link exception

A link exception allows you to associate another exception with an exception. The second exception describes the reason for the first exception.

To allow link exceptions, two constructors and two methods are added Throwable.

Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)

Here is an example of the mechanism for handling link exceptions:

public class Main {
  static void demoproc() {
    NullPointerException e = new NullPointerException("top layer");
    e.initCause(new ArithmeticException("cause"));
    throw e;
  }

  public static void main(String args[]) {
    try {
      demoproc();
    } catch (NullPointerException e) {
      System.out.println("Caught: " + e);
      System.out.println("Original cause: " + e.getCause());
    }
  }
}

Related Java Tutorials & Interview Questions

Related Java Tutorials & Interview Questions
Introduction to Java Programming Core Java Multiple Choice Questions
Java Keywords Tutorial For Beginners 21 Aricent Java Interview Questions
Java Data Types Tutorial For Beginners 53 Accenture Java Interview Questions
Java Operators Tutorial For Beginners 399 Core Java Interview Questions
Java Control Flow Statements Tutorial 581 Advanced Java Interview Questions
Java Performance Tuning Tips 60 Java Multiple Choice Questions And Answers
Java Class Tutorial For Beginners More Java Tutorials & Interview Questions..

 

Leave a Reply

Your email address will not be published. Required fields are marked *