In this tutorial, we will see examples of a few frequently used exceptions. If you looking for exception handling tutorial refer to this complete guide: Exception handling in Java.
In this tutorial, we will learn below Java built-in exceptions examples:
Example 1: Arithmetic Exception
In below example, ArithmeticException occurs when an integer is divided by zero.
package com.javaguides.corejava;
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 30 / 0; // Trying to divide by zero
} catch (ArithmeticException e) {
System.err.println("ArithmeticException caught!");
e.printStackTrace();
}
}
}
Output
ArithmeticException caught!
java.lang.ArithmeticException: / by zero
at com.javaguides.corejava.ArithmeticExceptionExample.main(ArithmeticExceptionExample
Read more at Java Arithmetic Exception Example
Example 2: ArrayIndexOutOfBoundsException
In this example, if an array is having only 3 elements and we are trying to display -1 or 4th element then it would throw this exception.
package com.javaguides.corejava;
public class ArrayIndexOutOfBounds {
public static void main(String[] args) {
int[] nums = new int[] {
1,
2,
3
};
try {
int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
int numFromGreaterIndex = nums[4]; // Trying to access at greater index
int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("ArrayIndexOutOfBoundsException caught");
e.printStackTrace();
}
}
}
Output
ArrayIndexOutOfBoundsException caught
java.lang.ArrayIndexOutOfBoundsException: -1
at com.javaguides.corejava.ArrayIndexOutOfBounds.main(ArrayIndexOutOfBounds.java:10)
Read more at Java ArrayIndexOutOfBoundsException Example
Example 3: ClassCastException
Here is a very simple example, an Integer object cannot be cast to a String object:
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = new Integer(100);
System.out.println((String) obj);
}
}
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)
Read more at ClassCastException Java Example
Example 4: ClassNotFoundException
Below example demonstrates the common causes of java.lang.ClassNotFoundException is using Class.forNameor ClassLoader.loadClass to load a class by passing the string name of a class and it’s not found on the classpath.
package com.javaguides.corejava;
public class ClassNotFoundExceptionExample {
public static void main(String[] args) {
try {
Class.forName("com.javaguides.corejava.Demo");
ClassLoader.getSystemClassLoader().loadClass("com.javaguides.corejava.Demo");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
java.lang.ClassNotFoundException: com.javaguides.corejava.Demo
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.javaguides.corejava.ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:9)
Read more at ClassNotFoundException Java Example
Example 5: FileNotFoundException
In this below example, invalid path location passed to File constructor leads to this exception.
package com.javaguides.corejava;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("/invalid/file/location")));
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException caught!");
e.printStackTrace();
}
}
}
Output:
FileNotFoundException caught!
java.io.FileNotFoundException: \invalid\file\location (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at com.javaguides.corejava.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:15)
Read more at FileNotFoundException Java Example
Example 6: IllegalStateException
In this example, the Iterator.remove() method throws an IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.
package com.javaguides.corejava;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IllegalStateExceptionExample {
public static void main(String[] args) {
List < Integer > intList = new ArrayList < > ();
for (int i = 0; i < 10; i++) {
intList.add(i);
}
Iterator < Integer > intListIterator = intList.iterator(); // Initialized with index at -1
try {
intListIterator.remove(); // IllegalStateException
} catch (IllegalStateException e) {
System.err.println("IllegalStateException caught!");
e.printStackTrace();
}
}
}
Output:
IllegalStateException caught!
java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(ArrayList.java:872)
at com.javaguides.corejava.IllegalStateExceptionExample.main(IllegalStateExceptionExample.java:21)
Read more at IllegalStateException in Java with Example
Example 7: InterruptedException
In the below example, note that thread interrupted in main() method throws InterruptedException exception that is handled in the run() method.
package com.javaguides.corejava;
class ChildThread extends Thread {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println("InterruptedException caught!");
e.printStackTrace();
}
}
}
public class InterruptedExceptionExample {
public static void main(String[] args) throws InterruptedException {
ChildThread childThread = new ChildThread();
childThread.start();
childThread.interrupt();
}
}
Output:
InterruptedException caught!
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.javaguides.corejava.ChildThread.run(InterruptedExceptionExample.java:7)
Read more at InterruptedException in Java with Example
Example 8: NullPointerException
In below example, the person object is null and we are invoking its fields on null object leads to NullPointerException.
package com.javaguides.corejava;
public class NullPointerExceptionExample {
public static void main(String[] args) {
Person personObj = null;
try {
String name = personObj.personName; // Accessing the field of a null object
personObj.personName = "Ramesh Fadatare"; // Modifying the field of a null object
} catch (NullPointerException e) {
System.err.println("NullPointerException caught!");
e.printStackTrace();
}
}
}
class Person {
public String personName;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
}
Output:
NullPointerException caught!
java.lang.NullPointerException
at com.javaguides.corejava.NullPointerExceptionExample.main(NullPointerExceptionExample.java:9)
Read more at NullPointerException Java Example
Example 9: NumberFormatException
In the below example, we are trying to parse "100ABCD" string into integer leads to NumberFormatException:package com.javaguides.corejava;
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String str1 = "100ABCD";
try {
int x = Integer.parseInt(str1); // Converting string with inappropriate format
int y = Integer.valueOf(str1);
} catch (NumberFormatException e) {
System.err.println("NumberFormatException caught!");
e.printStackTrace();
}
}
}
Output:
NumberFormatException caught!
java.lang.NumberFormatException: For input string: "100ABCD"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.javaguides.corejava.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)
Read more at NumberFormatException in Java Example
Example 10: ParseException
In this example, we use DateFormat.parse(String source) method which throws ParseException object.
This parse() method throws ParseException - if the beginning of the specified string cannot be parsed.
Here is a complete code to throw ParseException exception:
package com.javaguides.corejava;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ParseExceptionExample {
public static void main(String[] args) {
DateFormat format = new SimpleDateFormat("MM, dd, yyyy");
try {
format.parse("01, , 2010");
} catch (ParseException e) {
System.err.println("ParseException caught!");
e.printStackTrace();
}
}
}
Output:
ParseException caught!
java.text.ParseException: Unparseable date: "01, , 2010"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.javaguides.corejava.ParseExceptionExample.main(ParseExceptionExample.java:15)
Read more at ParseException in Java Example
Example 11: StringIndexOutOfBoundsException
In this below example, the exception occurred because the referenced index was not present in the String.
package com.javaguides.corejava;
public class StringIndexOutOfBounds {
public static void main(String[] args) {
String str = "Hello World";
try {
char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index
char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string
} catch (StringIndexOutOfBoundsException e) {
System.err.println("StringIndexOutOfBoundsException caught");
e.printStackTrace();
}
}
}
Output:
StringIndexOutOfBoundsException caught
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.charAt(String.java:658)
at com.javaguides.corejava.StringIndexOutOfBounds.main(StringIndexOutOfBounds.java:9)
Read more at StringIndexOutOfBoundsException in Java with ExampleCheck out complete exception handling tutorial at https://www.javaguides.net/p/java-exception-handling-tutorial.html.
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course