Built-in Exceptions in Java with examples
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:
1. Arithmetic exception : It is thrown when an exceptional condition has occurred in an arithmetic operation.
Java
// Java program to demonstrate // ArrayIndexOutOfBoundException class 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"); } } } |
v>
Output:
Can't divide a number by 0
2. 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
// FileNotFoundException
import 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:
Array Index is Out Of Bounds
3. ClassNotFoundException : This Exception is raised when we try to access a class whose definition is not found.
Java
// Java program to illustrate the // concept of ClassNotFoundException class Bishal { } class Beginner { } 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
4. FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
Java
// Java program to demonstrate // FileNotFoundException import 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
5. IOException : It is thrown when an input-output operation failed or interrupted
JAVA
<div id= "highlighter_103206" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" > // Java program to illustrate IOException</code></div><div class="line number2 index1 alt1"><code class="keyword">import</code> <code class="plain">java.io.*;</code></div><div class="line number3 index2 alt2"><code class="keyword">class</code> <code class="plain">Beginner {</code></div><div class="line number4 index3 alt1"><code class="keyword">public</code> <code class="keyword">static</code> <code class="keyword">void</code> <code class="plain">main(String args[])</code></div><div class="line number5 index4 alt2"><code class="undefined spaces"> </code><code class="plain">{</code></div><div class="line number6 index5 alt1"><code class="undefined spaces"> </code><code class="plain">FileInputStream f = </code><code class="keyword">null</code><code class="plain">;</code></div><div class="line number7 index6 alt2"><code class="undefined spaces"> </code><code class="plain">f = </code><code class="keyword">new</code> <code class="plain">FileInputStream("abc.txt");</code></div><div class="line number8 index7 alt1"><code class="undefined spaces"> </code><code class="keyword">int</code> <code class="plain">i;</code></div><div class="line number9 index8 alt2"><code class="undefined spaces"> </code><code class="keyword">while</code> <code class="plain">((i = f.read()) != -</code><code class="value">1</code><code class="plain">) {</code></div><div class="line number10 index9 alt1"><code class="undefined spaces"> </code><code class="plain">System.out.print((</code><code class="keyword">char</code><code class="plain">)i);</code></div><div class="line number11 index10 alt2"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number12 index11 alt1"><code class="undefined spaces"> </code><code class="plain">f.close();</code></div><div class="line number13 index12 alt2"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number14 index13 alt1"><code class="plain">}</code></div></div></td></tr></tbody></table></div> |
Output:
error: unreported exception IOException; must be caught or declared to be thrown
6. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
JAVA
<div id= "highlighter_216585" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" > // Java Program to illustrate </code></div><div class="line number2 index1 alt1"><code class="comments">// InterruptedException</code></div><div class="line number3 index2 alt2"><code class="keyword">class</code> <code class="plain">Beginner {</code></div><div class="line number4 index3 alt1"><code class="keyword">public</code> <code class="keyword">static</code> <code class="keyword">void</code> <code class="plain">main(String args[])</code></div><div class="line number5 index4 alt2"><code class="undefined spaces"> </code><code class="plain">{</code></div><div class="line number6 index5 alt1"><code class="undefined spaces"> </code><code class="plain">Thread t = </code><code class="keyword">new</code> <code class="plain">Thread();</code></div><div class="line number7 index6 alt2"><code class="undefined spaces"> </code><code class="plain">t.sleep(</code><code class="value">10000</code><code class="plain">);</code></div><div class="line number8 index7 alt1"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number9 index8 alt2"><code class="plain">}</code></div></div></td></tr></tbody></table></div> |
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
7. NoSuchMethodException : t is thrown when accessing a method which is not found.
JAVA
<div id= "highlighter_37259" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" > // Java Program to illustrate </code></div><div class="line number2 index1 alt1"><code class="comments">// NoSuchMethodException</code></div><div class="line number3 index2 alt2"><code class="keyword">class</code> <code class="plain">Beginner {</code></div><div class="line number4 index3 alt1"><code class="keyword">public</code> <code class="plain">Beginner()</code></div><div class="line number5 index4 alt2"><code class="undefined spaces"> </code><code class="plain">{</code></div><div class="line number6 index5 alt1"><code class="undefined spaces"> </code><code class="plain">Class i;</code></div><div class="line number7 index6 alt2"><code class="undefined spaces"> </code><code class="keyword">try</code> <code class="plain">{</code></div><div class="line number8 index7 alt1"><code class="undefined spaces"> </code><code class="plain">i = Class.forName("java.lang.String");</code></div><div class="line number9 index8 alt2"><code class="undefined spaces"> </code><code class="keyword">try</code> <code class="plain">{</code></div><div class="line number10 index9 alt1"><code class="undefined spaces"> </code><code class="plain">Class[] p = </code><code class="keyword">new</code> <code class="plain">Class[</code><code class="value">5</code><code class="plain">];</code></div><div class="line number11 index10 alt2"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number12 index11 alt1"><code class="undefined spaces"> </code><code class="keyword">catch</code> <code class="plain">(SecurityException e) {</code></div><div class="line number13 index12 alt2"><code class="undefined spaces"> </code><code class="plain">e.printStackTrace();</code></div><div class="line number14 index13 alt1"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number15 index14 alt2"><code class="undefined spaces"> </code><code class="keyword">catch</code> <code class="plain">(NoSuchMethodException e) {</code></div><div class="line number16 index15 alt1"><code class="undefined spaces"> </code><code class="plain">e.printStackTrace();</code></div><div class="line number17 index16 alt2"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number18 index17 alt1"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number19 index18 alt2"><code class="undefined spaces"> </code><code class="keyword">catch</code> <code class="plain">(ClassNotFoundException e) {</code></div><div class="line number20 index19 alt1"><code class="undefined spaces"> </code><code class="plain">e.printStackTrace();</code></div><div class="line number21 index20 alt2"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number22 index21 alt1"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number23 index22 alt2"> </div><div class="line number24 index23 alt1"><code class="keyword">public</code> <code class="keyword">static</code> <code class="keyword">void</code> <code class="plain">main(String[] args)</code></div><div class="line number25 index24 alt2"><code class="undefined spaces"> </code><code class="plain">{</code></div><div class="line number26 index25 alt1"><code class="undefined spaces"> </code><code class="keyword">new</code> <code class="plain">Beginner();</code></div><div class="line number27 index26 alt2"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number28 index27 alt1"><code class="plain">}</code></div></div></td></tr></tbody></table></div> |
Output:
error: exception NoSuchMethodException is never thrown in body of corresponding try statement
8. NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing
JAVA
// Java program to demonstrate // StringIndexOutOfBoundsException class 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:
NullPointerException..
9. NumberFormatException : This exception is raised when a method could not convert a string into a numeric format.
JAVA
<div id= "highlighter_612687" class = "syntaxhighlighter nogutter " ><table border= "0" cellpadding= "0" cellspacing= "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" > // Java program to demonstrate </code></div><div class="line number2 index1 alt1"><code class="comments">// NumberFormatException</code></div><div class="line number3 index2 alt2"><code class="keyword">class</code> <code class="plain">NumberFormat_Demo {</code></div><div class="line number4 index3 alt1"><code class="keyword">public</code> <code class="keyword">static</code> <code class="keyword">void</code> <code class="plain">main(String args[])</code></div><div class="line number5 index4 alt2"><code class="undefined spaces"> </code><code class="plain">{</code></div><div class="line number6 index5 alt1"><code class="undefined spaces"> </code><code class="keyword">try</code> <code class="plain">{</code></div><div class="line number7 index6 alt2"><code class="undefined spaces"> </code><code class="comments">// "akki" is not a number</code></div><div class="line number8 index7 alt1"><code class="undefined spaces"> </code><code class="keyword">int</code> <code class="plain">num = Integer.parseInt("akki");</code></div><div class="line number9 index8 alt2"> </div><div class="line number10 index9 alt1"><code class="undefined spaces"> </code><code class="plain">System.out.println(num);</code></div><div class="line number11 index10 alt2"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number12 index11 alt1"><code class="undefined spaces"> </code><code class="keyword">catch</code> <code class="plain">(NumberFormatException e) {</code></div><div class="line number13 index12 alt2"><code class="undefined spaces"> </code><code class="plain">System.out.println("Number format exception");</code></div><div class="line number14 index13 alt1"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number15 index14 alt2"><code class="undefined spaces"> </code><code class="plain">}</code></div><div class="line number16 index15 alt1"><code class="plain">}</code></div></div></td></tr></tbody></table></div> |
Output:
Number format exception
10. StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the string.
JAVA
// Java Program to illustrate // StackOverflowError class Test { public static void main(String[] args) { m1(); } public static void m1() { m2(); } public static void m2() { m1(); } } |
Output:
StringIndexOutOfBoundsException
Some other important Exceptions
1. ClassCastException
JAVA
// Java Program to illustrate // NoClassDefFoundError class Test // { public static void main(String[] args) { System.out.println("HELLO Beginner"); } } |
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
2. StackOverflowError
JAVA
// Java Program to illustrate // ExceptionInInitializerError class Test { static int x = 10 / 0 ; public static void main(String[] args) { } } |
Output:
Exception in thread "main" java.lang.StackOverflowError
3. NoClassDefFoundError
JAVA
// Java Program to illustrate // ExceptionInInitializerError class Test { static { String s = null ; System.out.println(s.length()); } public static void main(String[] args) { } } |
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
4. ExceptionInInitializerError
Code 1:
JAVA
// Java Program to illustrate // IllegalArgumentException class 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.ExceptionInInitializerError Caused by: java.lang.ArithmeticException: / by zero
Code 2 :
JAVA
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.
5. IllegalArgumentException
JAVA
// Java Program to illustrate // IllegalArgumentException class 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.
6. IllegalThreadStateException
JAVA
public void setAge( int age) { if (age < 0 || age > 120 ) { throw new IllegalArgumentException( "Invalid age" ); } this .age = age; } |
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.
7. AssertionError
JAVA
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.
IllegalArgumentException: This exception is thrown when an illegal argument is passed to a method. For example:
Java
public void setAge( int age) { if (age < 0 || age > 120 ) { throw new IllegalArgumentException( "Invalid age" ); } this .age = age; } |
FileNotFoundException: This exception is thrown when a file cannot be found. For example:
Java
try { FileReader reader = new FileReader( "file.txt" ); // throws FileNotFoundException } catch (FileNotFoundException e) { System.out.println( "File not found" ); } |
Contact Us