You are currently viewing Java Exception with Example

Java Exception with Example

In this tutorial, you will learn about Java Exception, Exception Hierarchy, Java Exception Types, and Catching Exceptions with an Example.

What is Java Exception?

An exception is defined in Java as “an event that occurs during the execution of a program that disrupts the normal flow of instructions.” This is a generally unexpected or undesirable event that can occur in application code at compile-time or run-time.

An exception (or exceptional event) is a problem that occurs while a program is being executed. When an exception occurs, the normal flow of the program is disrupted, and the program/Application terminates abnormally, which is not recommended; thus, these exceptions must be handled.

An exception can occur for a variety of reasons. The following are some examples of when an exception occurs.

  • A user entered incorrect information.
  • A file that needs to be opened is missing.
  • A network connection has been lost in the middle of communication, or the JVM has reached its memory limit.

Some of these exceptions are the result of user error, while others are the result of programmer error, and still, others are the result of physical resources that have failed in some way.

We have three types of Exceptions based on these. To understand how exception handling works in Java, you must first understand them.

  1. Checked exceptions
  2. Unchecked exceptions
  3. Errors

Checked exceptions are exceptions that are checked (notified) by the compiler at compilation time, these are also known as compile-time exceptions. These exceptions cannot be ignored instead, the programmer must take care of (handle) them.

Unchecked exceptions An unchecked exception is one that occurs during execution. Runtime Exceptions are another name for this. Programming bugs, such as logic errors or improper use of an API, are examples of this. Runtime exceptions are ignored during compilation.

Errors are not exceptions, but rather problems that occur outside of the user’s or programmer’s control. Errors are typically ignored in your code because they are rarely correctable. An error will occur, for example, if a stack overflow occurs. They are also ignored during compilation.

Exception Hierarchy

All exception classes are subclasses of java.lang.Exception. The Throwable class is a subclass of the Exception class. Aside from the exception class, another subclass derived from the Throwable class is Error.

Errors are abnormal conditions that occur when there is a severe failure; these are not handled by Java programs. Errors are generated to indicate errors that the runtime environment causes. JVM, for example, has run out of memory. Normally, programs are unable to recover from errors.

The following is a list of the most frequently checked and unchecked Java Built-in Exceptions.

Exceptions Methods

The Throwable class contains a number of useful methods, which are listed below.

Sr.No.Method & Description
1public String getMessage()-This method returns a detailed message about the exception that occurred. The Throwable constructor is used to initialize this message.
2public Throwable getCause()-The cause of the exception, as represented by a Throwable object, is returned.
3public String toString()-Concatenates the class name with the result of getMessage to return the class name ().
4public void printStackTrace()-Prints the result of toString() along with the stack trace to System.err, the error output stream.
5public StackTraceElement [] getStackTrace()– Each element on the stack trace is represented as an array. The method at the top of the call stack is represented by the element at index 0, and the method at the bottom of the call stack is represented by the last element in the array.
6public Throwable fillInStackTrace()-Fills the current stack trace of this Throwable object, overwriting any previous information in the stack trace.

Java Exception Types

There are two branches in the exception hierarchy: RuntimeException and IOException.


A programming error causes a runtime exception. Unchecked exceptions are another name for them.

These exceptions are checked at run-time rather than compile-time. The following are some of the most common runtime exceptions:

  • IllegalArgumentException is thrown when an API is used incorrectly.
  • NullPointerException – NullPointerException – NullPointerException – NullPointerException – NullPointerException – NullPointerException – NullPointerException – NullPointer
  • ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException ArrayInde
  • ArithmeticException: Dividing a number by 0

This is how you can think about it. “It’s your fault if there’s a runtime exception.” If you had checked whether the variable was initialized before using it, the NullPointerException would not have occurred.

If you had checked the array index against the array bounds, you would not have gotten an ArrayIndexOutOfBoundsException.


A checked exception is another name for an IOException. They’re checked by the compiler at compile-time, and the programmer is prompted on how to handle them.

Checked exceptions include the following:

When attempting to open a file that does not exist, a FileNotFoundException is thrown.
Attempting to read a file past the end

Catching Exceptions

The try and catch keywords are used to catch an exception in a method. A try/catch block is used to surround code that could throw an exception. Protected code is code that is contained within a try/catch block, and the syntax for using try/catch is as follows:


try {
// Protected code
} catch (ExceptionName e1) {
// Catch block

The try block contains the code that is prone to exceptions. When an exception occurs, the catch block associated with it is used to handle it. Every try block should be followed immediately by a catch or finally block.

The type of exception you’re trying to catch is declared in a catch statement. The catch block (or blocks) that follow the try are checked if an exception occurs in protected code. If a catch block exists for the type of exception that occurred, the exception is passed to the catch block in the same way that an argument is passed to a method parameter.

Example: An array with two elements is declared as follows. The code then tries to access the array’s third element, which results in an exception.

public class TryCatch {

   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
      System.out.println("Out of the block");


Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple Catch Blocks

Multiple catch blocks can be placed after a try block. The following is the syntax for multiple catch blocks.


try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block

The previous statements show three catch blocks, but after a single try, you can have any number of them. If there is an exception in the protected code, it is thrown to the first catch block in the list. If the thrown exception’s data type matches ExceptionType1, it is caught there. If this is not the case, the exception is passed to the second catch statement. This continues until the exception is caught or falls through all catches, at which point the current method is terminated and the exception is passed down the call stack to the previous method.

Example: This section of code demonstrates how to use multiple try/catch statements.

try {
   file = new FileInputStream(fileName);
   x = (byte);
} catch (IOException i) {
   return -1;
} catch (FileNotFoundException f)  {
   return -1;

You may like:

java exception, exception handling in java, a custom exception in java, exception hierarchy in java, types of exception in java, a user-defined exception in java, checked exception in exception, exception handling in java, a custom exception in java, exception hierarchy in java, types of exception in java, a user-defined exception in java, checked exception in exception, exception handling in java, custom exception in java, exception hierarchy in java, types of exception in java, user-defined exception in java, checked exception in java.

Java enum with Example

Java enum Constructor with Example

Java Inheritance with Example | Types of inheritance

Java final Keyword with Example

Not Equal Example in Java

Java Polymorphism with Example

Singleton Class in Java with Implementation and Example

Java Nested and Inner Class with Example

Hope this article will guide you to recognize all about Java Exceptions with Example that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

This Post Has 2 Comments

Leave a Reply