Open In App

Top 5 Exceptions in Java with Examples

Last Updated : 09 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Top-5-Exceptions-in-Java-with-Examples

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 alternatives is nothing but exception handling.  

Types of Exceptions in Java

Exceptions are divided into two types. These are 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:

  • Generic programming exceptions: Generic programmatic exceptions are referred to those exceptions which are raised explicitly by the programmer (or) by the API developer are called programmatic exceptions. Examples include IllegalArgumentException(IAE)
     
  • 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




// 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);
    }
}


Output:

IllegalArgumentException(IAE)

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




// 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]);
    }
}


Output:

ArrayIndexOutOfBoundsException

3. StackOverFlowError

StackOverflowError is an error that Java doesn’t allow to catch, for instance, a 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




// 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();
    }
}


Output:

StackOverFlowError

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




// NumberFormatException in Java
  
// Importing input output java classes
import java.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");
    }
}


Output:

NumberFormatException

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




// 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());
    }
}


Output:

NullPointerException

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads