English English French French Spanish Spanish German German
Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

Exception Handling in Java: Explained

Exception-Handling-in-Java-Explained
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Exception Handling in Java is one of the most important concepts you will learn as a Java developer! This tutorial helps you understand and implement exception handling properly.

Every computer program has a specific flow in which it executes. If something unexpected happens, it leads to a disturbance in the normal flow of the program.

For example, the division of any numeric value by zero or accessing an index that doesn’t exist in an array. This phenomenon is termed as an exception in programming.

In simple words, an exception is something that you didn’t expect to happen but it can happen and you then need to handle it.

Why does an exception occur?

The key point here is possibility. There are multiple things that could go wrong. Network state, user interaction, invalid inputs, etc., are some of the things which could lead to an exception. What’s important is how you handle those exceptions which you think will occur sometime in some way or the other.

Exception Handling by JVM

When an exception occurs inside a java program, an object is created which describes the exception, including its type and state of the program when it occurred. This object is then passed to the Java Virtual Machine (JVM). The JVM tries to find a method or function to handle the exception. It goes through a list of methods that can potentially handle the exception.

exception-handling-method.
Image Credit: Oracle

Once it finds the appropriate method to handle the exception, it hands over the exception to the method, but if it can’t find an appropriate method, it terminates the program by calling the default exception-handling method.

Types of Exceptions in Java

Types-of-Exceptions-in-Java

Exceptions in java are of two types:

Checked: These types of exceptions are caught by the compiler at the compile time. Some of the checked exceptions in java include IOException and SQLException.

Unchecked: The compiler is unaware of these exceptions at compile time because they become evident at runtime. They are verified when the code gets executed. Unchecked exceptions include ArrayIndexOutOfBoundsException and IllegalStateException.

Ways to Handle an Exception

Here are some ways in which you can handle or throw an exception:

  • try… catch block
  • throw/throws keyword

#1. try… catch block

The try-catch block is used to run a piece of code in which there is a possibility that an exception can occur. The try and catch blocks are two separate blocks of code – catch block runs when the try block fails to execute normally.

try {
  // normal code
} catch(Exception e) {
  // code which handles an exception
}

There’s also a finally block which you can use to execute some code regardless an exception occurs or not. The code in this block will run in every case.

try {
  // normal code
} catch(Exception e) {
  // code which handles an exception
} finally {
  // some code
}

#2. throw & throws keyword

The throw keyword is used to explicitly create a single exception. You can use throw keyword if you know an exception can definitely occur for a particular condition.

public static void occur() {
  // condition
  throw new ArithmeticException();
}

public static void main(String[] args) {
  try {
    occur();
  } catch(Exception e) {
    // handle
  }
}

You can use the throws keyword to state multiple exceptions which you know will occur in a given method.

public static void occur() throws Exception1, Exception2, Exception3 {
  // conditions which throw different exceptions
}

public static void main(String[] args) {
  try {
    occur();
  } catch(Exception1 e) {
    //...
  } catch(Exception2 e) {
    //...
  } catch(Exception3 e) {
    //...
  }
}

Some Common Exceptions in Java

Some-Common-Exceptions-in-Java

#1. IOException

An IOException can occur in java if there is a problem with the input/output process. It usually occurs when you are trying to access a file and its contents but the file doesn’t exist or there is a problem with reading the content inside it.

import java.io.FileNotFoundException;
import java.io.FileReader;

public class Main {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("hello.txt");
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }
}

#2. ArrayIndexOutOfBoundsException

An array is a data structure which stores values of the same data type and each value has an index which starts from 0 and goes up to (n-1) where n is the total number of values present in the array. You can access an element by specifying the index with the name of the variable referencing the array:

array[index]

Now, if you try to access an element with an index less than 0 or greater than (n-1), an exception will occur because there is no element at that particular index. This type of exception is known as ArrayIndexOutOfBoundsException and it occurs at runtime.

public class Main {
    public static void main(String[] args) {
        try {
            int[] arr = {34, 1, 78, 3, 5};
            int element = arr[7];
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

#3. ClassCastException

This type of exception occurs when you try to typecast the object of a parent class with the type of one of it’s subclass. You can also get this exception if you try to typecast an object with a class with which it’s not compatible.

class A {
    public void display() {
        System.out.println("This is class A");
    }
}

class B extends A {
    public void display() {
        System.out.println("This is class B which is a subclass of A");
    }
}

class C extends B {
    public void display() {
        System.out.println("This is class C which is a subclass of B");
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            A objA = new A();
            B objB = (B) new A();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

The above code will throw a ClassCastException because we are trying to typecast an object of parent class with the type of its subclass.

#4. IllegalArgumentException

When a method or a function receives an argument that is not valid, it can throw an IllegalArgumentException. For example, let’s say you are creating a method to calculate the perimeter of a square.

While requesting the length of a side of the square from the user, if you get a negative value, then you can throw this exception because a square’s side can’t be negative.

public class Main {
    public static int perimeter(int length) {
        if(length < 0) {
            throw new IllegalArgumentException("No negative values are allowed!");
        }
        return 4 * length;
    }

    public static void main(String[] args) {
        try {
            System.out.println(perimeter(-5));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

#5. IllegalStateException

When you call a method or a function at a time at which it should not be called, you get an IllegalStateException. For example, if you call the start method on a thread that has already been started, then java will throw this exception at runtime.

class AThread extends Thread {
    public void run() {
        System.out.println("This is a thread!");
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            AThread t = new AThread();
            t.start();
            t.start();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

#6. NullPointerException

It occurs when you try to access properties of a null object or a variable pointing to a null value. Null is a special value in java which indicates that no value is assigned to a referencing variable.

public class Main {
    public static void main(String[] args) {
        try {
            String num = null;
            System.out.println(num.length());
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

#7. NumberFormatException

It occurs when you try to convert an improperly formatted string to a number. For example, if you try to convert “null” or “twenty” into a number, then java will throw this exception.

public class Main {
    public static void main(String[] args) {
        try {
            int num = Integer.parseInt("12,389");
            System.out.println(num);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Conclusion

Handling exceptions is important because they can create unnecessary interruptions in the flow of the program. Note that exceptions are different from errors because exceptions should be handled, whereas errors can’t be handled. Instead, they should be resolved or fixed. You can learn more about java by going through these online Java courses.

Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Semrush is an all-in-one digital marketing solution with more than 50 tools in SEO, social media, and content marketing.
    Try Semrush
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder