Advertisement

Exception handling in Java

What is Exception Handling in Java?

Exception handling in java help us in reducing exceptions and helps in recovering from exceptions. It is one of the powerful mechanisms of java language to handle runtime exceptions and makes it error-free. Exception handling helps us in maintaining the flow of the program. An abnormal condition that may happen at runtime and disturb the normal flow of the program is known as exception handling.

exception handling in java


What is an Exception?

An expectation is an unexpected (in programming it usually occur from user side) event that occurs while running the program, that disturbs/terminate the normal flow of the code.

Exception handling in java with an example:

Let’s say,

statement
statement
statement
exception …… an exception occurred, then JVM (Java Virtual Machine) will handle it and will exit the program.
statement
statement
statement

We have 2 possible approaches for handling exception

1. JVM

JVM stands for Java Virtual Machine, If an exception is not handled categorically, then JVM takes the responsibility/assignment of handling the exception.

Once the exception is handled, JVM will halt the program and no more running of program will take place

  • Example:
import java.util.*;

class Main { public static void main (String[] args) { System.out.println(4/0); System.out.println("Stop the program!"); }
}

Runtime Error:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(File.java:5)

2Developer

Developers can categorically write the implementation for handling the exception. Once an exception is handled, the normal execution of program will continue.

Java Exception Hierarchy

Following is the Exception Handling in Java handling hierarchy.

  • Throwable 
    • This is the root class for the exception hierarchy in java. 
    • It is in the package java.lang.
  • Error 
    • it is a subclass of Throwable.
    • it consist of abnormal condition that is out control and depends on the environment
    • They cannot be handled and will always result in the halting in the execution of the program.
  • Exception 
    • it is aslo a subclass of Throwable.
    • it consist of abnormal conditions that can be handled categorically.
    • If one handles the exception then our program will continue to execute smoothly.

Types of exception in Java

  • Checked Exceptions
    • The exceptions that are checked at compile-time known as checked exceptions.
    • They are child classes of Exception except for RuntimeException.
    • The program will stop and not compile if they are not handled.
    • Example: IOException, ClassNotFoundException, etc.
  • Unchecked Exceptions
    • Those exceptions that are checked at runtime known as unchecked exceptions.
    • They are child classes of RuntimeException.
    • They give runtime errors (usually wrong input by user) if not handled explicitly.
    • Example: ArithmeticException, NullPointerException etc.

Difference between Checked and Unchecked Exception

Checked ExceptionsUnchecked Exceptions
this occur at compile time.this occur at runtime.
The compiler checks for a checked exception.The compiler doesn’t check for exceptions.
Can be handled at the compilation time.Can’t be caught or handled during compilation time.
The JVM requires that the exception be caught and handled.The JVM doesn’t require the exception to be caught and handled.
Example of Checked exception- ‘File Not Found Exception’Example of Unchecked Exceptions- ‘No Such Element Exception’


Java Exception Keywords

we use keywords: try, catch, throw, throws, and finally for exception handling in java. 

KeywordDescription
trytry is used to specify a block and this block must another part either catch or finally. We cannot use try block alone.
catchcatch keyword must be preceded by a try block to handle the exception and can be followed by a final block.
finallyfinally keyword is used to run the program, an exception is handled or not but finally block must execute.
throwwe use throw keyword to throw an exception.
throwswe use throws keyword to declare exceptions.

Java Try-Catch Block

Try-catch syntax:

try{
}
catch(Exception e){
}
  • Try-catch Example:
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
System.out.println(a/i);
}catch(ArithmeticException e){
System.out.println(e);
}
}
}

Output:

3
5
10
java.lang.ArithmeticException: / by zero
  • try block contains the source code that might throw an exception. Do not write anything extra in try block as statements after the exception will not get executed if the exception occurred. Try must be followed by catch block or finally block.
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
System.out.println(a/i);
}
}
}

Compile-time error:

prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations
  try{
  ^
1 error
  • The catch part is used to catch the exception thrown by statements in the try block. The catch must follow try else it will give a compile-time error.
public class ExceptionDemo {
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
try{
System.out.println(a/i);
}
System.out.println("between try and catch");
catch(ArithmeticException e){
System.out.println(e);
}
}
}

Compile Time Error:

prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations
  try{
  ^
prog.java:9: error: 'catch' without 'try'
  catch(ArithmeticException e){
  ^
2 errors

Things to Remember:

Do not write any code after the statement which is prone to exception. Because if an exception occurred, it will straight jump away to the catch or finally block, ignoring/skipping all other statements in the try block.

class Main {
public static void main (String[] args) {
try
{
System.out.println(4/0);
//will not get printed
System.out.println("end of try!");
}
catch(ArithmeticException e)
{
System.out.println("divide by 0");
}
}
}

Output:

divide by 0
  • While catching the exception in the catch block, either you can have directly the class of exception or its superclass.

Example: Exact Exception

class Main {
public static void main (String[] args) {
try{
System.out.println(4/0);
}
//ArithmeticException
catch(ArithmeticException e){
System.out.println("divide by 0");
}
}
}

Output:

divide by 0

Example: Superclass of Exact Exception

class Main {
public static void main (String[] args) {
try{
System.out.println(4/0);
}
//superclass of ArithmeticException
catch(Exception e){
System.out.println("divide by 0");
}
}
}

Output:

divide by 0

Java Multiple Catch Block

If you have multiple catches in your code, you have to maintain the hierarchy from subclass to superclass accordingly.

Incorrect:

class Main {
public static void main (String[] args) {
try{
System.out.println(4/0);
}catch(Exception e)
{
System.out.println("Exception : divide by 0");
}catch(ArithmeticException e)
{
System.out.println("ArithmeticException :divide by 0");
}
}
}

Compile-time error:

prog.java:11: error: exception ArithmeticException has already been caught
        }catch(ArithmeticException e)
         ^
1 error

Correct:

class Main {
public static void main (String[] args) {
try{
System.out.println(4/0);
}catch(ArithmeticException e)
{
System.out.println("ArithmeticException : divide by 0");
}catch(Exception e)
{
System.out.println("Exception : divide by 0");
}
}
}

Output:

ArithmeticException: Divide by 0

Java Nested Try

When there is a try block inside another try block:

class Main {
public static void main (String[] args) {
try{
try{
int[] a={1,2,3};
System.out.println(a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Out of bounds");
}
System.out.println(4/0);
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException : divide by 0");
}
}
}

Output:

Out of bounds
ArithmeticException: Divide by 0

Note – If we write code of outer try before inner try block, then if an exception occurred, it will ignore/skip the entire inner try and move directly to its catch block.

class Main {
public static void main (String[] args) {
try{
System.out.println(4/0);
try{
int[] a={1,2,3};
System.out.println(a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Out of bounds");
}
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException : divide by 0");
}
}
}

Output:

ArithmeticException: Divide by 0

Java Finally Block

code in this block must be executed either if an exception is thrown or not.

  • Example:
class Main {
public static void main (String[]args) {
try{
System.out.println(4/0);
}catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("finally executed");
}
System.out.println("end");
}
}

Output:

java.lang.ArithmeticException: / by zero
finally executed
end

Even, finally block will execute when we do not handle exceptions. Before stoping the program, JVM checks if there is a “finally” block if found that jump to finally block.

class Main {
public static void main (String[]args) {
try{
System.out.println(4/0);
}finally
{
System.out.println("cleaning.......");
}
}
}

Runtime Error:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(File.java:4)

Output:

cleaning.......

Java Final vs Finally vs Finalize

FinalFinallyFinalize
For restrictions on class, method, and variable we use Final keyword.Finally is used in coding, it will be executed no matter an exception is handled or not.Finalize is used for clean-up processing before garbage is collected.
Final is a keyword in javaFinally is a block in javaFinalize is a method in java
after calling Final is will executed.After ”try-catch” block Finally executes.finalize run just before the destruction/ending of the object.

Java Throw Keyword

It is a keyword that is used to throw an exception.

We can use throw where according to our logic.

Example:

public class ExceptionDemo {
static void canVote(int age){
if(age<18)
try{
throw new Exception();
}catch(Exception e){
System.out.println("you are not an adult!");
}
else
System.out.println("you can vote!");
}
public static void main (String[]args) {
canVote(20);
canVote(10);
}
}

Output:

you can vote!
you are not an adult!

Java Throws Keyword

  • Throws keyword is used when called doesn’t want to handle the exception rather it wants to extend this responsibility of handling the exception to the caller of the function.
  • Basically says what sort of exception the code can throw and relies on the caller to handle it.
  • It is used to handle checked Exceptions as the compiler will not allow code to compile until they are handled.

Example:

public class ExceptionDemo {
static void func(int a) throws Exception{
System.out.println(10/a);
}
public static void main (String[]args) {
try{
func(10);
func(0);
}catch(Exception e){
System.out.println("can't divide by zero");
}
}
}

Output:

1
can't divide by zero

If callee can throw multiple exceptions, then all will be thrown simultaneously.

import java.util.*;

public class ExceptionDemo { static void func(int a,int b) throws ArithmeticException, ArrayIndexOutOfBoundsException{ System.out.println(10/a); int[] arr={1,2,3}; System.out.println(arr[b]); } public static void main (String[]args) { Scanner in=new Scanner(System.in); for(int i=0;i<3;i++){ try{ func(in.nextInt(),in.nextInt()); }catch(ArithmeticException e){ System.out.println("can't divide by zero"); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Out of bounds!"); } } }
}

Input:

2 1
0 1
2 3

Output:

5
2
can't divide by zero
5
Out of bounds!

Java Throw vs Throws

ThrowThrows
we use Throw to throw an exception.we use Throws to declare an exception.
A checked exception cannot be propagated with throw only.A checked exception can be propagated with throws.
The throw is followed by an instance and used with a methodThrows are followed by class and used with the method signature.
You cannot throw multiple exceptions.You can declare multiple exceptions


Post a Comment

0 Comments