Types of Exception in Java With Best Examples

Types of Exception in Java :- There are Two Type Of Exception in Java.

  1. Compile Time Exception or Checked Exception.
  2. Run Time Exception or Unchecked Exception.

Compile Time Exception or Checked Exception

Compile Time Exception : – This Exception Occur When dot Java File is Converted to dot class File. There are Many Type of Compile Time Exception.

  • FileNotFoundException
  • SQLException
  • IOException
  • ClassNotFoundException
  • ClonedNotSupportedExcepton

Run Time Exception or Unchecked Exception

Run Time Exception: – This Exception occur When You Run dot class File. There Are Many Type Of Run Time Exception.

  • ArithmeticExcepton
  • NullPointerException
  • NumberFormatException
  • ArrayIndexOutOfBoundsExcepton
  • ClassCastException

You Also Learn –

Exception Class Hierarchy Diagram

Types of Exception in Java
Diagram 1 : Types of Exception in Java

Types of Exception in Java With Examples

  1. ArithmeticException : – It Helps us to Handle Arithmetic Related Exception Like Dividing a Number by Zero.

Example 1

public class A   {
public static void main ( String[] args ) {
try {
int x=10;
int y=0;
int z=x/y;          // Error
System.out.println(z);
System.out.println(10);
} catch (ArithmeticException e ) {
e.printStackTrace();
}
System.out.println(100);
}
}
Output :
java.lang.ArithmeticException: / by zero
100
	at A.main(A.java:6)

2. NullPointerException: – When You Access Non-Static Members With Null Reference Variable than We Get NullPointerException Which Can Be Handled Using NullPointerException Class.

Example 2

public class A   {
static A a1;    //null
int x=10;       // non static variable
public static void main ( String[] args ) {
try {
System.out.println(a1.x);
} catch (NullPointerException e ) {
e.printStackTrace();
}
System.out.println(100);
}
}
Output : 
java.lang.NullPointerException: Cannot read field "x" because "A.a1" is null
	at A.main(A.java:6)
100

3. NumberFormatException: – When an Invalid String to Number Conversion is Done. We, will, Get NumberFormatException As shown in the Below Example.

public class A   {
public static void main(String[] args) {
	try {
		String x = "abcd";
		int y = Integer.parseInt(x);
		System.out.println(y);
	}
	catch (NumberFormatException e) {
		e.printStackTrace();
	}
	System.out.println(1000);
}
}
Output :
java.lang.NumberFormatException: For input string: "abcd"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:668)
	at java.base/java.lang.Integer.parseInt(Integer.java:786)
	at A.main(A.java:5)
1000

Leave a Comment