Zeek_80A_Types of Exceptions in Java


Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked.

 An error is considered as the unchecked exception.

 However,

 According to Oracle, there are three types of exceptions namely:


--> Checked Exception

--> Unchecked Exception

--> Error 


Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions

 For example, IOException, SQLException, etc.

Checked exceptions are checked at compile-time.


2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions.

 For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc

 Unchecked exceptions are not checked at compile-time, but they are checked at runtime.


3) Error

Error is irrecoverable.

 Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.


UNCHECKED EXCEPTIONS


Some scenarios where unchecked exceptions may occur.

 They are as follows:

--> A scenario where ArithmeticException occurs

    If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0; //ArithmeticException  


--> A scenario where NullPointerException occurs

   If we have a null value in any variable

    , performing any operation on the variable throws a NullPointerException.

String s=null;  
System.out.println(s.length()); //NullPointerException

    

--> A scenario where NumberFormatException occurs

    If the formatting of any variable or number is mismatched, it may result into 

   NumberFormatException

Suppose we have a string variable that has characters; converting this variable into 

digit will cause NumberFormatException.

String s="abc";  
int i=Integer.parseInt(s); //NumberFormatException

    

--> A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. 

    there may be other reasons to occur ArrayIndexOutOfBoundsException.

int a[]=new int[5];  
a[10]=50; //ArrayIndexOutOfBoundsException  





Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:







Hierarchy of Java Exception Class





Comments

Popular posts from this blog

Zeek_31_MethodInJava.java