In this article, we will discuss top exception and error in java with their description & examples
Top Exception in Java:
1. Null Pointer Exception
Exception Name : | NullPointerException |
Fully qualified name : | java.lang.NullPointerException |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.RuntimeException
- JVM raises NullPointerException, whenever operation is performed on null reference
- For example, if we have an un-initialized String variable then trying to check or get its length using length() method throws/raises NullPointerException
- See below example for reference
StringOperationForCheckingLength.java
package in.bench.resources.top.exception.in.java;
public class StringOperationForCheckingLength {
public static void main(String[] args) {
// string variable
String str = null;
// checking length
int len = str.length();
// printing to console
System.out.println("Length of str is : " + len);
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at in.bench.resources.top.exception.in.java
.StringOperationForCheckingLength.main(
StringOperationForCheckingLength.java:11)
2. Array Index Out Of Bounds Exception
Exception Name : | ArrayIndexOutOfBoundsException |
Fully qualified name : | java.lang.ArrayIndexOutOfBoundsException |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.IndexOutOfBoundsException, which is sub-class of java.lang.RuntimeException
- JVM raises ArrayIndexOutOfBoundsException, whenever we are trying to perform operation like accessing or assigning an array element with out-of-range of index
- That’s index is greater than length of an array or index with negative value
- For example, if original length of an array is 5 then trying to assign/access a value at 7th index-position, raises/throws ArrayIndexOutOfBoundsException
- See below example for reference
ArrayOperationOnInvalidIndex.java
package in.bench.resources.top.exception.in.java;
public class ArrayOperationOnInvalidIndex {
public static void main(String[] args) {
// character array of length 5
char[] ch = new char[5];
// assigning value at 7th index-psotion
ch[7] = 'B';
// printing to console
System.out.println("The value at 7th index-position is : " + ch[7]);
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at in.bench.resources.top.exception.in.java
.ArrayOperationOnInvalidIndex.main(
ArrayOperationOnInvalidIndex.java:11)
3. Arithmetic Exception
Exception Name : | ArithmeticException |
Fully qualified name : | java.lang.ArithmeticException |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.RuntimeException
- JVM raises ArithmeticException, whenever we perform invalid arithmetic operation like divide by zero, which throws ArithmeticException with “divide by zero” as exception description
- For example, performing a division with divisor as zero, throws/raises ArithmeticException as stated above
- See below example for reference
DivideByZeroExample.java
package in.bench.resources.top.exception.in.java;
public class DivideByZeroExample {
public static void main(String[] args) {
// performing division
int quotient = 19/0;
// printing to console
System.out.println("The quotient after division is : " + quotient);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at in.bench.resources.top.exception.in.java.DivideByZeroExample
.main(DivideByZeroExample.java:8)
4. Class Cast Exception
Exception Name : | ClassCastException |
Fully qualified name : | java.lang.ClassCastException |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.RuntimeException
- JVM raises ClassCastException, whenever we are trying to do invalid type-casting
- That’s type-casting from super-class type to sub-class type, throws/raises ClassCastException at runtime (although compilation succeeds)
- In simple words, when RHS Object doesn’t satisfy “IS-A” relationship with LHS, then this exception is raised
- For example, assigning Object-type to String-type results in type-casting exception at runtime
- See below example for reference
ClassCastExceptionExample.java
package in.bench.resources.top.exception.in.java;
public class ClassCastExceptionExample {
public static void main(String[] args) {
// Object-type
Object object = new Object();
// assigning Object-type to String-type
String str = (String) object;
// printing to console
System.out.println("String is : " + str);
}
}
Output:
Exception in thread "main" java.lang.ClassCastException:
java.lang.Object cannot be cast to java.lang.String
at in.bench.resources.top.exception.in.java.ClassCastExceptionExample
.main(ClassCastExceptionExample.java:11)
5. Illegal Argument Exception
Exception Name : | IllegalArgumentException |
Fully qualified name : | java.lang.IllegalArgumentException |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.RuntimeException
- IllegalArgumentException is raised because of passing wrong/invalid argument to a method
- For example, setting Thread priority to more than integer value 10 or negative value results in this type of exception
- Because valid range for Thread priority is 1 to 10
- See below example for reference
InvalidArgumentForThreadPriority.java
package in.bench.resources.top.exception.in.java;
public class InvalidArgumentForThreadPriority {
public static void main(String[] args) {
// create a new Thread
Thread t = new Thread();
// set wrong/invalid priority
t.setPriority(11);
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException
at java.lang.Thread.setPriority(Unknown Source)
at in.bench.resources.top.exception.in.java
.InvalidArgumentForThreadPriority
.main(InvalidArgumentForThreadPriority.java:11)
6. Number format Exception
Exception Name : | NumberFormatException |
Fully qualified name : | java.lang.NumberFormatException |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.IllegalArgumentException, which is child-class of java.lang.RuntimeException
- NumberFormatException is raised when we try to convert string to numeric value like integer, float, double, etc and string passed isn’t properly formatted
- For example, if we pass numeric 10 as string to parseInt() method of Integer class, then it convert into numeric value 10
- Whereas trying to convert string value of “ben” to integer, results in NumberFormatException
- See below example for reference
ParseStringToInteger.java
package in.bench.resources.top.exception.in.java;
public class ParseStringToInteger {
public static void main(String[] args) {
// VALID - trying to convert string into integer value
int resultValid = Integer.parseInt("10");
System.out.println("The Value is : " + resultValid);
// INVALID - trying to convert string into integer value
int resultInvalid = Integer.parseInt("ben");
System.out.println("The Value is : " + resultInvalid);
}
}
Output:
The Value is : 10
Exception in thread "main" java.lang.NumberFormatException:
For input string: "ben"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at in.bench.resources.top.exception.in.java.ParseStringToInteger
.main(ParseStringToInteger.java:12)
7. Illegal Thread State Exception
Exception Name : | IllegalThreadStateException |
Fully qualified name : | java.lang.IllegalThreadStateException |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.IllegalArgumentException, which is child-class of java.lang.RuntimeException
- IllegalThreadStateException is raised when we try to start the Thread again, when it is already in started state
- For example, invoking start() method of Thread 2nd time results in IllegalThreadStateException
- See below example for reference
StartingThreadAgain.java
package in.bench.resources.top.exception.in.java;
public class StartingThreadAgain {
public static void main(String[] args) {
// create a new Thread
Thread t = new Thread();
// 1st time - starting Thread
t.start();
// 2nd time - starting Thread AGAIN
t.start();
}
}
Output:
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at in.bench.resources.top.exception.in.java.StartingThreadAgain
.main(StartingThreadAgain.java:14)
8. Interrupted Exception
Exception Name : | InterruptedException |
Fully qualified name : | java.lang.InterruptedException |
Exception Type : | Checked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.Exception
- Generally, this exception-type is encountered whenever we are working with threading or multi-threading programming
- Being checked exception, it need to be handled either by try-catch block or declare exception using throws clause
- Sleep() & join() method of Thread class & wait() method of Object class throw this exception
- For example, invoking interrupt on a Thread which is in sleeping/waiting state results in throwing this exception-type
- See below example for reference
InterruptingThread.java
package in.bench.resources.top.exception.in.java;
public class InterruptingThread {
public static void main(String[] args) {
// create a new Thread
Thread t = new Thread(){
public void run() {
try {
Thread.sleep(5000);
}
catch (InterruptedException iex) {
iex.printStackTrace();
}
}
};
// start a Thread
t.start();
// interrupt a Thread
t.interrupt();
}
}
Output:
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at in.bench.resources.top.exception.in.java.InterruptingThread$1
.run(InterruptingThread.java:13)
9. File Not Found Exception
Exception Name : | FileNotFoundException |
Fully qualified name : | java.io.FileNotFoundException |
Exception Type : | Checked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.io.IOException
- Whenever we are working with file, then it is must to handle FileNotFoundException
- Because sometime it is possible that accessing file location isn’t available or else file itself not available at the specified location
- For example, trying to access a file from specified location but file isn’t available at that location
- See below example for reference
FileProcessing.java
package in.bench.resources.top.exception.in.java;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FileProcessing {
public static void main(String[] args) throws FileNotFoundException {
// performing IO operation
// assumed that, we are trying to access file from remote location
FileReader fileReader = new FileReader("D:/Folder/test.txt");
}
}
Output:
Exception in thread "main" java.io.FileNotFoundException:
D:\Folder\test.txt (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at in.bench.resources.top.exception.in.java.FileProcessing
.main(FileProcessing.java:12)
10. SQL Exception
Exception Name : | SQLException |
Fully qualified name : | java.lang.SQLException |
Exception Type : | Checked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.io.IOException
- After loading driver file for respective database, whenever we perform any operation with database and supplied credentials or database table/columns is incorrect
- Then this exception-type is raised
- For example, passing wrong database URL for a non-existent database results in rising SQLException
- See below example for reference
JdbcConnectionExample.java
package in.bench.resources.top.exception.in.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConnectionExample {
public static void main(String[] args) {
// declare variables
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
// Step 1: Loading or
// registering Oracle JDBC driver class
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException cnfex) {
System.out.println(
"Problem in loading Oracle JDBC driver");
cnfex.printStackTrace();
}
// Step 2: Opening database connection
try {
// Step 2.A: Create and
// get connection using DriverManager class
connection = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe",
"scott",
"tiger");
// Step 2.B: Creating JDBC Statement
statement = connection.createStatement();
// Step 2.C: Executing SQL and
// retrieve data into ResultSet
}
catch(SQLException sqlex){
sqlex.printStackTrace();
}
finally {
// Step 3: Closing database connection
}
}
}
Output:
java.sql.SQLException: Io exception:
The Network Adapter could not establish the connection
at oracle.jdbc.driver.DatabaseError.throwSqlException(
DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(
DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(
DatabaseError.java:255)
at oracle.jdbc.driver.T4CConnection.logon(
T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(
PhysicalConnection.java:414)
at oracle.jdbc.driver.T4CConnection.<init>(
T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(
T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(
OracleDriver.java:801)
at java.sql.DriverManager.getConnection(
Unknown Source)
at java.sql.DriverManager.getConnection(
Unknown Source)
at in.bench.resources.top.exception.in.java.JdbcConnectionExample
.main(JdbcConnectionExample.java:31)
11. Class Not Found Exception
Exception Name : | ClassNotFoundException |
Fully qualified name : | java.lang.ClassNotFoundException |
Exception Type : | Checked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.Exception
- Generally this exception raised, when we try to execute a program and required .class files is missing from class-path
- For example, trying to load driver file for respective databases but it isn’t available at runtime
- Possible reason for this type of exception is, executing a JDBC program without updating class-path with required JAR files
- See below example for reference
JdbcConnectionExample.java
package in.bench.resources.top.exception.in.java;
public class JdbcConnectionExample {
public static void main(String[] args) {
// declare variables
// Step 1: Loading or registering Oracle JDBC driver class
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException cnfex) {
System.out.println("Problem in loading Oracle JDBC driver");
cnfex.printStackTrace();
}
// Step 2: Opening database connection
}
}
Output:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
Problem in loading Oracle JDBC driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at in.bench.resources.top.exception.in.java.JdbcConnectionExample
.main(JdbcConnectionExample.java:11)
Top Error in Java:
12. No Class Def Found Error
Exception Name : | NoClassDefFoundError |
Fully qualified name : | java.lang.NoClassDefFoundError |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.LinkageError, which is child-class of java.lang.Error
- JVM raises NoClassDefFoundError, whenever we try to execute a program and required .class files is missing from class-path
- Possible reason for this type of exception is, required file is present during compilation but missing while executing the same program
- For example, below program exhibits “HAS-A” relationship & compilation succeeds whereas during program execution JVM unable to find required .class file
- See below example for reference
SimilarException.java
package in.bench.resources.top.exception.in.java;
public class SimilarException {
// using below declared TestFile class
static TestFile tf = new TestFile();
public static void main(String[] args) {
// invoke method
tf.display();
}
}
class TestFile {
public void display() {
System.out.println("Display message");
}
}
Output:
java.lang.NoClassDefFoundError:
in/bench/resources/top/exception/in/java/TestFile
at in.bench.resources.top.exception.in.java.SimilarException.<clinit>(
SimilarException.java:6)
Caused by: java.lang.ClassNotFoundException:
in.bench.resources.top.exception.in.java.TestFile
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
Exception in thread "main"
Q) Difference between ClassNotFoundException and NoClassDefFoundError ?
- ClassNotFoundException occurs, when we try to execute a program and required .class file isn’t available at runtime. Also, there won’t be compile-time error as we are trying to load class using Class.forName(“fully.qualified.name”);
- NoClassDefFoundError occurs, when we try to execute a program and required .class file isn’t available at runtime. Because required file was available during program compilation but missing while executing (for some reasons)
- Read ClassNotFoundException v/s NoClassDefFoundError for more details
13. Exception in Initializer Error
Exception Name : | ExceptionInInitializerError |
Fully qualified name : | java.lang.ExceptionInInitializerError |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.LinkageError, which is child-class of java.lang.Error
- JVM raises ExceptionInInitializerError, whenever we try perform some assignment operation in static variable or inside static blocks
- For example, printing length of a string variable inside static block where string variable is referencing to null reference, results in throwing ExceptionInInitializerError
- See below example for reference
ExceptionErrorDemo.java
package in.bench.resources.top.exception.in.java;
public class ExceptionErrorDemo {
// static block
static {
String str = null;
System.out.println("The length of string is : " + str.length());
}
// main() method - JVM execution start here
public static void main(String[] args) {
}
}
Output:
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at in.bench.resources.top.exception.in.java.ExceptionErrorDemo.<clinit>(
ExceptionErrorDemo.java:9)
Exception in thread "main"
14. Stack Overflow Error
Exception Name : | StackOverflowError |
Fully qualified name : | java.lang.StackOverflowError |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.VirtualMachineError, which is child-class of java.lang.Error
- JVM raises StackOverflowError, whenever we perform repeated recursive method call
- See below example for reference
RecursiveDemo.java
package in.bench.resources.top.exception.in.java;
public class RecursiveDemo {
// main() method - JVM execution starts here
public static void main(String[] args) {
// invoking methodA
methodA();
}
// method A - recursively invoking method B
public static void methodA() {
// invoking methodB
methodB();
}
// method B - recursively invoking method A
public static void methodB() {
// invoking methodA
methodA();
}
}
Output:
Exception in thread "main" java.lang.StackOverflowError
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodA(RecursiveDemo.java:16)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodB(RecursiveDemo.java:23)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodA(RecursiveDemo.java:16)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodB(RecursiveDemo.java:23)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodA(RecursiveDemo.java:16)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodB(RecursiveDemo.java:23)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodA(RecursiveDemo.java:16)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodB(RecursiveDemo.java:23)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodA(RecursiveDemo.java:16)
at in.bench.resources.top.exception.in.java.RecursiveDemo
.methodB(RecursiveDemo.java:23)
........
........
........
........
15. Assertion Error
Exception Name : | AssertionError |
Fully qualified name : | java.lang.AssertionError |
Exception Type : | Unchecked Exception |
Exception hierarchy : | See below figure |
Description:
- It is the direct sub-class of java.lang.Error
- Whenever we want to test our assumption, then JVM raises AssertionError if our assumption goes wrong (basically the other way of our assumption)
- This is mainly used in JUnit for testing purpose
- For example, in the below assertion test when user enters integer value less than 18 then our assumpotion fails
- And then accordingly JVM raises AssertionError
- Note: AssertionError can be thrown explicitly using throw keyword
- See below example for reference
AssertionTest.java
package in.bench.resources.top.exception.in.java;
import java.util.Scanner;
public class AssertionTest {
public static void main(String[] args) {
// for taking input from users
Scanner scanner = new Scanner(System.in);
System.out.print("Age for obtaning Driver License : ");
int value = scanner.nextInt();
// assertion test for Age
assert value>=18 : "Age should be more than 18 years old";
}
}
Output:
Age for obtaning Driver License : 16
Exception in thread "main" java.lang.AssertionError:
Age should be more than 18 years old
at in.bench.resources.top.exception.in.java.AssertionTest
.main(AssertionTest.java:15)
Related Articles:
- Java – Exception Handling
- Java – Exception Hierarchy
- Java – 5 important keywords in Java Exception handling
- Java – Runtime mechanism, what happens when exception is thrown ?
- Java – Checked Exception v/s Unchecked Exception
- Java – Exception propagation
- Java – try-catch block
- Java – finally block
- Java – try with multiple catch blocks
- Java – Nested try-catch block
- Java – Returning value from method having try-catch-finally blocks
- Java – return statement with finally block
- Java – final v/s finally v/s finalize
- Java – Various methods to print exception information
- Java – throw keyword
- Java – throws keyword
- Java – throw v/s throws
- Java – Difference between throws clause and try-catch-finally block
- Java – Rules for Exception handling w.r.t Method Overriding
- Java – User-defined or Custom exception
- Java – Difference between ClassNotFoundException v/s NoClassDefFoundError
- Java – Top Exception and Error
- Java – Interview question and answers on Exception Handling
- Java 7 – try with resources
- Java 7 – multi-catch block
References:
- http://www.oracle.com/technetwork/articles/java/java7exceptions-486908.html
- http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
- http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
- https://docs.oracle.com/javase/tutorial/essential/exceptions/
- https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
- https://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/ArithmeticException.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
- http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
- http://www.oracle.com/technetwork/java/effective-exceptions-092345.html
- http://otfried.org/courses/cs206/slides/slides-stackframes.pdf
Happy Coding !!
Happy Learning !!