Monday, November 15, 2021

Exception Handling in Java

An exception is defined as an abnormal condition that may happen at runtime and disturb the normal flow of the program.

An exception can occur for many different reasons. Following are some scenarios where an exception occurs.


  • A user has entered an invalid data.

  • A file that needs to be opened cannot be found.

  • A network connection has been lost in the middle of communications or the JVM has run out of memory.

The Exception Handling in Java is a mechanism to handle the runtime errors so that the normal flow of the application can be maintained.


There are three categories of exceptions:


  • Checked exceptions −
     a checked exception is an exception that is checked (notified) by thecompiler at compilation-time; these are also called as compile time exceptions. These exceptions should be taken care of (handle) by programmers.
  • Unchecked exceptions −
    an unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
  • Errors − these are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in code because rarely anything can be done about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Hierarchy of Java Exception classes

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.


Java Exception Keywords

Java provides five keywords that are used to handle the exception – try, catch, finally, throw, throws.

The ‘try’ keyword is used to specify a block where an exception code is placed and this block must be followed by either catch or finally.


The "catch" block is used to handle the exception. It must be preceded by try block. It can be followed by finally block later.


try {

  
// Protected code


} catch (ExceptionName e1) {

  
// Catch block


}


Ex:


import java.io.*;


public class ExcTest {

 
public static void main(String args[]) {

     
try {

         int a[] = new int[2];

         System.out.println("Access third element:" + a[3]);     

}catch (ArrayIndexOutOfBoundsException e) {

         System.out.println("Exception thrown  :" + e);

     
}

     
System.out.println("Out of the try block");

  
}


}


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following −


Syntax:


try {

  
// Protected code


} catch (ExceptionType1 e1) {

 
// Catch block


} catch (ExceptionType2 e2) {

 
// Catch block


} catch (ExceptionType3 e3) {

 
// Catch block


}


The "throw" keyword is used to throw an exception.


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);

            }

}


The "throws" keyword is used to declare exceptions. It specifies that an exception may occur in the method. It doesn't throw an exception. It is always used with method signature. Throws keyword is used when callee doesn’t want to handle the exception rather it wants to extend this responsibility of handling the exception to the caller of the function.


Ex:

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");


                        }      


            }


}


The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.


A finally block appears at the end of the catch blocks and has the following syntax –


try {

  
// Protected code


} catch (ExceptionType1 e1) {

// Catch block


} catch (ExceptionType2 e2) {

  
// Catch block


} catch (ExceptionType3 e3) {


// Catch block


}finally {

  
// The finally block always executes.


}

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top