Skip to content
Related Articles

Related Articles

Top 5 Exceptions in Java with Examples
  • Last Updated : 19 Jan, 2021

An unwanted unexpected event that disturbs the normal execution of the program after getting compiled while running is called an exception. In order to deal with such abrupt execution of the program, exception handling is the normal termination of the program. 

Top-5-Exceptions-in-Java

Illustration: Considering a real-life example

Suppose books requirement is from Delhi library at runtime if Delhi library is not available to provide books due to some transport issues. Then Delhi library suggests taking books from Indore library to continue the rest of our work. This way of defining alternative is nothing but exception handling.  

Exceptions are divided as follows:

  1. Checked exceptions: These are the exceptions that can be detected by the compiler at the time of execution of the program and warning messages are displayed.
     
  2. Unchecked Exceptions: These are the exceptions that are missed out from the compiler check giving birth to abrupt flow.No warning messages are displayed as these exceptions are not detected by the compiler.

Now the above two types of exceptions are categorized as follows:



  1. Generic programming exceptions: Generic programmatic exception are referred to those exceptions which are raised explicitly by the programmer (or) by the API developer are called programmatic exceptions. Example include IllegalArgumentException(IAE)
  2. JVM exceptions: Exceptions are referred to as those exceptions which are raised automatically by the JVM (Java Virtual Machine) whenever a particular event occurs. Examples are ArrayIndexOutOfBoundsException and NullPointException(NPE).

The top 5 exceptions that occur most are as follows:

  1. IllegalArgumentException
  2. ArrayOutOfBoundException
  3. StackOverflowException
  4. NumberFormatException
  5. NullPointerException

1. IllegalArgumentException(IAE) 

It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Example:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// IllegalArgumentException in Java
  
// Class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating a new thread
        Thread t = new Thread();
  
        // valid in thread
        t.setPriority(10);
  
        // invalid(IllegalArgumentException(IAE))
        t.setPriority(100);
    }
}

chevron_right


Output:

2. ArrayIndexOutOfBoundsException

The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.



Example:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// ArrayIndexOutOfBoundsException in Java
  
// Importing all classes of
// java.util package
import java.util.*;
  
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Size of array is 10
        // Indexes ranging [00 - 09]
        int[] a = new int[10];
  
        // Case 1: Custom index within array size
        // Valid
        System.out.println(a[0]);
  
        // Case 2: Index greater than the size of the array
        // Invalid
        // ArrayIndexOutOfBoundsException
        System.out.println(a[100]);
  
        // ArrayIndexOutOfBoundsException
        System.out.println(a[-100]);
    }
}

chevron_right


Output:

3. StackOverFlowError

StackOverflowError is an error which Java doesn’t allow to catch, for instance, stack running out of space, as it’s one of the most common runtime errors one can encounter. The main cause of the StackOverflowError is that we haven’t provided the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop.

Example:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// StackOverflowException in Java
  
// Importing all classes of 
// java.util package
import java.util.*;
  
// Class
public class GFG {
  
    // Method1()
    public static void methodOne()
  
    {
        // Defining Method2() in Method1()
        methodTwo();
    }
  
    // Method2()
    public static void methodTwo()
  
    {
        // Calling method1 in methos2()
        methodOne();
    }
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Calling method1() in main()
        methodOne();
    }
}

chevron_right


Output:

4. NumberFormatException:

This exception is thrown when forcefully string is been converted to numeric value but the format of the input string is not supported. For example, parsing a string to an integer where NULL is assigned in the string throwing unchecked exceptions.

Example:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// NumberFormatException in Java
  
// Importing input output java classes
import jav.io.*;
  
// Class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // ParseInt() takes integer value as parameter
        // other values
  
        // valid
        int i = Integer.parseInt("50");
  
        // invalid
        // forInputString(A)
        // NumberFormatException will be thrown
        int j = Integer.parseInt("A");
  
        // invalid
        // forInputString(five)
        // NumberFormatException will be thrown
        int k = Integer.parseInt("five");
    }
}

chevron_right


Output:

5. NullPointerException

Null is a special value used in Java. It is mainly used to indicate that no value is assigned to a reference variable. It is a runtime Exception where a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value.

Example:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// NullPointerException in Java
  
// Importing all classes of
// java.util package
import java.util.*;
  
// Class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Assigning null to string
        String str = null;
  
        // Calculating length of string
  
        // Forcefully printing length which throws
        // NullPointerException
        System.out.println(str.length());
    }
}

chevron_right


Output:

Note:: There are two more exceptions that do occurs frequently

  1.   NoClassDefFound where the definition for the corresponding class is missing
  2. ClassCastException is runtime exception where a class is improperly casted from one type to another.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :