Built-in Exceptions in Java with examples

04 Jul, 2020
Types of Exceptions in Java
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.Examples of Built-in Exception:
Arithmetic exception : It is thrown when an exceptional condition has occurred in an arithmetic operation.// Java program to demonstrate // ArithmeticExceptionclass ArithmeticException_Demo {public static void main(String args[])    {        try {            int a = 30, b = 0;            int c = a / b; // cannot divide by zero            System.out.println("Result = " + c);        }        catch (ArithmeticException e) {            System.out.println("Can't divide a number by 0");        }    }}Output:Can't divide a number by 0
ArrayIndexOutOfBounds Exception : 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.// Java program to demonstrate // ArrayIndexOutOfBoundExceptionclass ArrayIndexOutOfBound_Demo {public static void main(String args[])    {        try {            int a[] = new int[5];            a[6] = 9; // accessing 7th element in an array of            // size 5        }        catch (ArrayIndexOutOfBoundsException e) {            System.out.println("Array Index is Out Of Bounds");        }    }}Output:Array Index is Out Of BoundsClassNotFoundException : This Exception is raised when we try to access a class whose definition is not found.// Java program to illustrate the // concept of ClassNotFoundExceptionclass Bishal {  } class Geeks {  } class MyClass {public static void main(String[] args)    {        Object o = class.forName(args[0]).newInstance();        System.out.println("Class created for" + o.getClass().getName());    }}Output:ClassNotFoundExceptionFileNotFoundException : This Exception is raised when a file is not accessible or does not open.// Java program to demonstrate // FileNotFoundExceptionimport java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;class File_notFound_Demo {  public static void main(String args[])    {        try {              // Following file does not exist            File file = new File("E:// file.txt");              FileReader fr = new FileReader(file);        }        catch (FileNotFoundException e) {            System.out.println("File does not exist");        }    }}Output:File does not existIOException : It is thrown when an input-output operation failed or interrupted// Java program to illustrate IOExceptionimport java.io.*;class Geeks {public static void main(String args[])    {        FileInputStream f = null;        f = new FileInputStream("abc.txt");        int i;        while ((i = f.read()) != -1) {            System.out.print((char)i);        }        f.close();    }}Output:error: unreported exception IOException; must be caught or declared to be thrown
InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.// Java Program to illustrate // InterruptedExceptionclass Geeks {public static void main(String args[])    {        Thread t = new Thread();        t.sleep(10000);    }}Output:error: unreported exception InterruptedException; must be caught or declared to be thrown
NoSuchMethodException : t is thrown when accessing a method which is not found.// Java Program to illustrate // NoSuchMethodExceptionclass Geeks {public Geeks()    {        Class i;        try {            i = Class.forName("java.lang.String");            try {                Class[] p = new Class[5];            }            catch (SecurityException e) {                e.printStackTrace();            }            catch (NoSuchMethodException e) {                e.printStackTrace();            }        }        catch (ClassNotFoundException e) {            e.printStackTrace();        }    }  public static void main(String[] args)    {        new Geeks();    }}Output:error: exception NoSuchMethodException is never thrown 
in body of corresponding try statement
NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing// Java program to demonstrate NullPointerExceptionclass NullPointer_Demo {public static void main(String args[])    {        try {            String a = null; // null value            System.out.println(a.charAt(0));        }        catch (NullPointerException e) {            System.out.println("NullPointerException..");        }    }}Output:NullPointerException..
NumberFormatException : This exception is raised when a method could not convert a string into a numeric format.// Java program to demonstrate // NumberFormatExceptionclass NumberFormat_Demo {public static void main(String args[])    {        try {            // "akki" is not a number            int num = Integer.parseInt("akki");              System.out.println(num);        }        catch (NumberFormatException e) {            System.out.println("Number format exception");        }    }}Output:Number format exception
StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the string.// Java program to demonstrate // StringIndexOutOfBoundsExceptionclass StringIndexOutOfBound_Demo {public static void main(String args[])    {        try {            String a = "This is like chipping "; // length is 22            char c = a.charAt(24); // accessing 25th element            System.out.println(c);        }        catch (StringIndexOutOfBoundsException e) {            System.out.println("StringIndexOutOfBoundsException");        }    }}Output:StringIndexOutOfBoundsException

Arithmetic exception : It is thrown when an exceptional condition has occurred in an arithmetic operation.// Java program to demonstrate // ArithmeticExceptionclass ArithmeticException_Demo {public static void main(String args[])    {        try {            int a = 30, b = 0;            int c = a / b; // cannot divide by zero            System.out.println("Result = " + c);        }        catch (ArithmeticException e) {            System.out.println("Can't divide a number by 0");        }    }}Output:Can't divide a number by 0

// Java program to demonstrate // ArithmeticExceptionclass ArithmeticException_Demo {public static void main(String args[])    {        try {            int a = 30, b = 0;            int c = a / b; // cannot divide by zero            System.out.println("Result = " + c);        }        catch (ArithmeticException e) {            System.out.println("Can't divide a number by 0");        }    }}
Output:
Can't divide a number by 0

ArrayIndexOutOfBounds Exception : 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.// Java program to demonstrate // ArrayIndexOutOfBoundExceptionclass ArrayIndexOutOfBound_Demo {public static void main(String args[])    {        try {            int a[] = new int[5];            a[6] = 9; // accessing 7th element in an array of            // size 5        }        catch (ArrayIndexOutOfBoundsException e) {            System.out.println("Array Index is Out Of Bounds");        }    }}Output:Array Index is Out Of Bounds
// Java program to demonstrate // ArrayIndexOutOfBoundExceptionclass ArrayIndexOutOfBound_Demo {public static void main(String args[])    {        try {            int a[] = new int[5];            a[6] = 9; // accessing 7th element in an array of            // size 5        }        catch (ArrayIndexOutOfBoundsException e) {            System.out.println("Array Index is Out Of Bounds");        }    }}
Output:
Array Index is Out Of Bounds
ClassNotFoundException : This Exception is raised when we try to access a class whose definition is not found.// Java program to illustrate the // concept of ClassNotFoundExceptionclass Bishal {  } class Geeks {  } class MyClass {public static void main(String[] args)    {        Object o = class.forName(args[0]).newInstance();        System.out.println("Class created for" + o.getClass().getName());    }}Output:ClassNotFoundException
// Java program to illustrate the // concept of ClassNotFoundExceptionclass Bishal {  } class Geeks {  } class MyClass {public static void main(String[] args)    {        Object o = class.forName(args[0]).newInstance();        System.out.println("Class created for" + o.getClass().getName());    }}
Output:
ClassNotFoundException
FileNotFoundException : This Exception is raised when a file is not accessible or does not open.// Java program to demonstrate // FileNotFoundExceptionimport java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;class File_notFound_Demo {  public static void main(String args[])    {        try {              // Following file does not exist            File file = new File("E:// file.txt");              FileReader fr = new FileReader(file);        }        catch (FileNotFoundException e) {            System.out.println("File does not exist");        }    }}Output:File does not exist
// Java program to demonstrate // FileNotFoundExceptionimport java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;class File_notFound_Demo {  public static void main(String args[])    {        try {              // Following file does not exist            File file = new File("E:// file.txt");              FileReader fr = new FileReader(file);        }        catch (FileNotFoundException e) {            System.out.println("File does not exist");        }    }}
Output:
File does not exist
IOException : It is thrown when an input-output operation failed or interrupted// Java program to illustrate IOExceptionimport java.io.*;class Geeks {public static void main(String args[])    {        FileInputStream f = null;        f = new FileInputStream("abc.txt");        int i;        while ((i = f.read()) != -1) {            System.out.print((char)i);        }        f.close();    }}Output:error: unreported exception IOException; must be caught or declared to be thrown

// Java program to illustrate IOExceptionimport java.io.*;class Geeks {public static void main(String args[])    {        FileInputStream f = null;        f = new FileInputStream("abc.txt");        int i;        while ((i = f.read()) != -1) {            System.out.print((char)i);        }        f.close();    }}
Output:
error: unreported exception IOException; must be caught or declared to be thrown

InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.// Java Program to illustrate // InterruptedExceptionclass Geeks {public static void main(String args[])    {        Thread t = new Thread();        t.sleep(10000);    }}Output:error: unreported exception InterruptedException; must be caught or declared to be thrown

// Java Program to illustrate // InterruptedExceptionclass Geeks {public static void main(String args[])    {        Thread t = new Thread();        t.sleep(10000);    }}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown

NoSuchMethodException : t is thrown when accessing a method which is not found.// Java Program to illustrate // NoSuchMethodExceptionclass Geeks {public Geeks()    {        Class i;        try {            i = Class.forName("java.lang.String");            try {                Class[] p = new Class[5];            }            catch (SecurityException e) {                e.printStackTrace();            }            catch (NoSuchMethodException e) {                e.printStackTrace();            }        }        catch (ClassNotFoundException e) {            e.printStackTrace();        }    }  public static void main(String[] args)    {        new Geeks();    }}Output:error: exception NoSuchMethodException is never thrown 
in body of corresponding try statement

// Java Program to illustrate // NoSuchMethodExceptionclass Geeks {public Geeks()    {        Class i;        try {            i = Class.forName("java.lang.String");            try {                Class[] p = new Class[5];            }            catch (SecurityException e) {                e.printStackTrace();            }            catch (NoSuchMethodException e) {                e.printStackTrace();            }        }        catch (ClassNotFoundException e) {            e.printStackTrace();        }    }  public static void main(String[] args)    {        new Geeks();    }}
Output:
error: exception NoSuchMethodException is never thrown 
in body of corresponding try statement

NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing// Java program to demonstrate NullPointerExceptionclass NullPointer_Demo {public static void main(String args[])    {        try {            String a = null; // null value            System.out.println(a.charAt(0));        }        catch (NullPointerException e) {            System.out.println("NullPointerException..");        }    }}Output:NullPointerException..

// Java program to demonstrate NullPointerExceptionclass NullPointer_Demo {public static void main(String args[])    {        try {            String a = null; // null value            System.out.println(a.charAt(0));        }        catch (NullPointerException e) {            System.out.println("NullPointerException..");        }    }}
Output:
NullPointerException..

NumberFormatException : This exception is raised when a method could not convert a string into a numeric format.// Java program to demonstrate // NumberFormatExceptionclass NumberFormat_Demo {public static void main(String args[])    {        try {            // "akki" is not a number            int num = Integer.parseInt("akki");              System.out.println(num);        }        catch (NumberFormatException e) {            System.out.println("Number format exception");        }    }}Output:Number format exception

// Java program to demonstrate // NumberFormatExceptionclass NumberFormat_Demo {public static void main(String args[])    {        try {            // "akki" is not a number            int num = Integer.parseInt("akki");              System.out.println(num);        }        catch (NumberFormatException e) {            System.out.println("Number format exception");        }    }}
Output:
Number format exception

StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the string.// Java program to demonstrate // StringIndexOutOfBoundsExceptionclass StringIndexOutOfBound_Demo {public static void main(String args[])    {        try {            String a = "This is like chipping "; // length is 22            char c = a.charAt(24); // accessing 25th element            System.out.println(c);        }        catch (StringIndexOutOfBoundsException e) {            System.out.println("StringIndexOutOfBoundsException");        }    }}Output:StringIndexOutOfBoundsException

// Java program to demonstrate // StringIndexOutOfBoundsExceptionclass StringIndexOutOfBound_Demo {public static void main(String args[])    {        try {            String a = "This is like chipping "; // length is 22            char c = a.charAt(24); // accessing 25th element            System.out.println(c);        }        catch (StringIndexOutOfBoundsException e) {            System.out.println("StringIndexOutOfBoundsException");        }    }}
Output:
StringIndexOutOfBoundsException

Some other important Exceptions
ClassCastException// Java Program to illustrate// ClassCastExceptionclass Test {public static void main(String[] args)    {        String s = new String("Geeks");        Object o = (Object)s;        Object o1 = new Object();        String s1 = (String)o1;    }}Output:Exception in thread "main" java.lang.ClassCastException: 
java.lang.Object cannot be cast to java.lang.String
StackOverflowError// Java Program to illustrate // StackOverflowErrorclass Test {public static void main(String[] args)    {        m1();    }public static void m1()    {        m2();    }public static void m2()    {        m1();    }}Output:Exception in thread "main" java.lang.StackOverflowError
NoClassDefFoundError// Java Program to illustrate// NoClassDefFoundErrorclass Test //    {public static void main(String[] args)    {        System.out.println("HELLO GEEKS");    }}Output:Note: If the corresponding Test.class file is not found 
during compilation then we will get Run-time Exception
saying Exception in thread "main" java.lang.NoClassDefFoundError
ExceptionInInitializerErrorCode 1:// Java Program to illustrate // ExceptionInInitializerErrorclass Test {    static int x = 10 / 0;public static void main(String[] args)    {    }}Output:Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
Code 2 :// Java Program to illustrate // ExceptionInInitializerErrorclass Test {    static    {        String s = null;        System.out.println(s.length());    }public static void main(String[] args)    {    }}Output:Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
Explanation : The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs.IllegalArgumentException// Java Program to illustrate // IllegalArgumentExceptionclass Test {public static void main(String[] args)    {        Thread t = new Thread();        Thread t1 = new Thread();        t.setPriority(7); // Correct        t1.setPriority(17); // Exception    }}Output:Exception in thread "main" java.lang.IllegalArgumentException
Explanation:The Exception occurs explicitly either by the programmer or by API developer to indicate that a method has been invoked with Illegal Argument.IllegalThreadStateException// Java Program to illustrate // IllegalStateExceptionclass Test {public static void main(String[] args)    {        Thread t = new Thread();        t.start();        t.start();    }}Output:Exception in thread "main" java.lang.IllegalThreadStateException
Explanation : The above exception rises explicitly either by programmer or by API developer to indicate that a method has been invoked at wrong time.AssertionError// Java Program to illustrate // AssertionErrorclass Test {public static void main(String[] args)    {        // If x is not greater than or equal to 10        // then we will get the run-time exception        assert(x >= 10);    }}Output:Exception in thread "main" java.lang.AssertionError
Explanation : The above exception rises explicitly by the programmer or by API developer to indicate that assert statement fails.
ClassCastException// Java Program to illustrate// ClassCastExceptionclass Test {public static void main(String[] args)    {        String s = new String("Geeks");        Object o = (Object)s;        Object o1 = new Object();        String s1 = (String)o1;    }}Output:Exception in thread "main" java.lang.ClassCastException: 
java.lang.Object cannot be cast to java.lang.String

// Java Program to illustrate// ClassCastExceptionclass Test {public static void main(String[] args)    {        String s = new String("Geeks");        Object o = (Object)s;        Object o1 = new Object();        String s1 = (String)o1;    }}
Output:
Exception in thread "main" java.lang.ClassCastException: 
java.lang.Object cannot be cast to java.lang.String

StackOverflowError// Java Program to illustrate // StackOverflowErrorclass Test {public static void main(String[] args)    {        m1();    }public static void m1()    {        m2();    }public static void m2()    {        m1();    }}Output:Exception in thread "main" java.lang.StackOverflowError

// Java Program to illustrate // StackOverflowErrorclass Test {public static void main(String[] args)    {        m1();    }public static void m1()    {        m2();    }public static void m2()    {        m1();    }}
Output:
Exception in thread "main" java.lang.StackOverflowError

NoClassDefFoundError// Java Program to illustrate// NoClassDefFoundErrorclass Test //    {public static void main(String[] args)    {        System.out.println("HELLO GEEKS");    }}Output:Note: If the corresponding Test.class file is not found 
during compilation then we will get Run-time Exception
saying Exception in thread "main" java.lang.NoClassDefFoundError

// Java Program to illustrate// NoClassDefFoundErrorclass Test //    {public static void main(String[] args)    {        System.out.println("HELLO GEEKS");    }}
Output:
Note: If the corresponding Test.class file is not found 
during compilation then we will get Run-time Exception
saying Exception in thread "main" java.lang.NoClassDefFoundError

ExceptionInInitializerErrorCode 1:// Java Program to illustrate // ExceptionInInitializerErrorclass Test {    static int x = 10 / 0;public static void main(String[] args)    {    }}Output:Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
Code 2 :// Java Program to illustrate // ExceptionInInitializerErrorclass Test {    static    {        String s = null;        System.out.println(s.length());    }public static void main(String[] args)    {    }}Output:Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
Explanation : The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs.
// Java Program to illustrate // ExceptionInInitializerErrorclass Test {    static int x = 10 / 0;public static void main(String[] args)    {    }}
Output:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero

Code 2 :
// Java Program to illustrate // ExceptionInInitializerErrorclass Test {    static    {        String s = null;        System.out.println(s.length());    }public static void main(String[] args)    {    }}
Output:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException

Explanation : The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs.
IllegalArgumentException// Java Program to illustrate // IllegalArgumentExceptionclass Test {public static void main(String[] args)    {        Thread t = new Thread();        Thread t1 = new Thread();        t.setPriority(7); // Correct        t1.setPriority(17); // Exception    }}Output:Exception in thread "main" java.lang.IllegalArgumentException
Explanation:The Exception occurs explicitly either by the programmer or by API developer to indicate that a method has been invoked with Illegal Argument.
// Java Program to illustrate // IllegalArgumentExceptionclass Test {public static void main(String[] args)    {        Thread t = new Thread();        Thread t1 = new Thread();        t.setPriority(7); // Correct        t1.setPriority(17); // Exception    }}
Output:
Exception in thread "main" java.lang.IllegalArgumentException

Explanation:The Exception occurs explicitly either by the programmer or by API developer to indicate that a method has been invoked with Illegal Argument.
IllegalThreadStateException// Java Program to illustrate // IllegalStateExceptionclass Test {public static void main(String[] args)    {        Thread t = new Thread();        t.start();        t.start();    }}Output:Exception in thread "main" java.lang.IllegalThreadStateException
Explanation : The above exception rises explicitly either by programmer or by API developer to indicate that a method has been invoked at wrong time.
// Java Program to illustrate // IllegalStateExceptionclass Test {public static void main(String[] args)    {        Thread t = new Thread();        t.start();        t.start();    }}
Output:
Exception in thread "main" java.lang.IllegalThreadStateException

Explanation : The above exception rises explicitly either by programmer or by API developer to indicate that a method has been invoked at wrong time.
AssertionError// Java Program to illustrate // AssertionErrorclass Test {public static void main(String[] args)    {        // If x is not greater than or equal to 10        // then we will get the run-time exception        assert(x >= 10);    }}Output:Exception in thread "main" java.lang.AssertionError
Explanation : The above exception rises explicitly by the programmer or by API developer to indicate that assert statement fails.
// Java Program to illustrate // AssertionErrorclass Test {public static void main(String[] args)    {        // If x is not greater than or equal to 10        // then we will get the run-time exception        assert(x >= 10);    }}
Output:
Exception in thread "main" java.lang.AssertionError

Explanation : The above exception rises explicitly by the programmer or by API developer to indicate that assert statement fails.
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Abhinav_27
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.