0% found this document useful (0 votes)
6 views

Unit_2_Exception

Exception handling in Java is a mechanism to manage runtime errors and maintain the normal flow of applications. It involves two main types of exceptions: checked and unchecked, with specific keywords like try, catch, and finally used to handle them. The document also explains how exceptions are thrown, caught, and the significance of the finally block in ensuring certain code executes regardless of exceptions.

Uploaded by

Tanmay Vaij
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit_2_Exception

Exception handling in Java is a mechanism to manage runtime errors and maintain the normal flow of applications. It involves two main types of exceptions: checked and unchecked, with specific keywords like try, catch, and finally used to handle them. The document also explains how exceptions are thrown, caught, and the significance of the finally block in ensuring certain code executes regardless of exceptions.

Uploaded by

Tanmay Vaij
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Exception Handling in Java

The exception handling in java is one of the powerful mechanism to


handle the runtime errors so that normal flow of the application can be
maintained.

What is exception?
 Exception is an abnormal condition.
 In java, exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.

What is exception handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, InterruptedException, etc.

Advantage of Exception Handling


 The core advantage of exception handling is to maintain the normal
flow of the application.

Example: Suppose there is 10 statements in your program and there


occurs an exception at statement 5, rest of the code will not be executed
i.e. statement 6 to 10 will not run. If we perform exception handling, rest
of the statement will be executed. That is why we use exception handling
in java.

Exception Hierarchy
Types of Exception
There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says
there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions


1) Checked Exception
The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions
e.g.IOException, SQLException etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are
checked at runtime.
3) Error
Error is irrecoverable
e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur


There are given some scenarios where unchecked exceptions can occur.
They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
Int a=50/0; //ArithmeticException

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the
variable occurs an NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException.
Suppose I have a string variable that have characters, converting this
variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws

How JVM handle an Exception?


 Whenever an exception occurs, the method creates an Exception
Object and hands it off to the run-time system (JVM).
 Exception object: name, description of the exception, current state
of the program where exception has occurred.
 Creating the Exception Object and handling it to the run-time system
is called throwing an Exception.
 There might be the list of the methods that had been called to get to
the method where exception was occurred.
This ordered list of the methods is called Call Stack. Now the
following procedure will happen.
-- JVM searches the call stack to find the method that contains block
of code that can handle the occurred exception. The block of the code
is called Exception handler.
-- If it finds appropriate handler then it passes the occurred exception
to it.
-- Appropriate handler means the type of the exception object thrown
matches the type of the exception object it can handle.
-- If JVM couldn’t find the appropriate handler then it handover the
Exception Object to default exception handler, which is part of
JVM.
-- This handler prints the exception information and terminates
program abnormally.

----------------------------------------------------------------------------------------
Catching Exceptions
 There are two ways to handle exceptions
 Declare exception using throws keyword
 Handle them using try/catch block

 Method which may generate exception can throw exception letting


system handle it.
 A try/catch block is placed around the code that might generate an
exception.
 Code within a try/catch block is referred to as protected code

Syntax:
try
{
// Protected code
}
catch(ExceptionName e1)
{
// Catch block
}

 The code that may generate exceptions is placed in the try block.
 When an exception occurs, it is handled by catch block associated
with it.
 Every try block should be immediately followed either by a catch
block or finally block.
 A catch declares the type of exception.
 If the type of exception that occurred is listed in a catch block, the
exception is passed to the catch block as an argument.
Example: try/catch block
public class demo
{
public static void main(String args[])
{
try
{
int a[] = new int[2];
System.out.println(a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown:" + e);
}
}
}

Example: Exception handling using throws keyword


public class demo
{
public static void main(String args[]) throws Exception
{
String str = null;
System.out.println(str.length());
}
}
Catching Run-Time Exceptions
 These are not checked at compile time.
 If your program is throwing an unchecked exception, the program won’t
give a compilation error.
 Most of the times these exception occurs due to the bad data provided
by user.
 It is programmer’s duty to judge the conditions in advance, that can
cause such exceptions and handle them appropriately.
 All Unchecked exceptions are direct sub classes of RuntimeException
class.

Example:
class Example
{
public static void main(String args[])
{
int num1=10;
int num2=0;
int res=num1/num2;
System.out.println(res);
}
}
(* This program would compile successfully but will give error at runtime)

 Run time exceptions can also be handled using try/catch block or


Throws keyword.
class Example
{
public static void main(String args[])
{
int num1=10;
int num2=0;
try
{
int res=num1/num2;
System.out.println(res);
}

catch(Exception e)
{
System.out.println(e);
}
System.out.println("Program executed with exception.");
}
}

(* Output will be exception message followed by statement mentioned


in SOP. If we do not catch exception, statement will not be printed.)

-----------------------------------------------------------------------------------

Multiple catch blocks

A try block can be followed by multiple catch blocks.

Syntax:
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3)
{
// Catch block
}
Example:
class Example
{
public static void main(String args[])
{
int num1=10;
int num2=0;
try
{
int res=num1/num2;
System.out.println(res);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(NumberFormatException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}

---------------------------------------------------------------------------------------

Catching Multiple Type of Exceptions


Since Java 7, you can handle more than one exception using a single catch
block, this feature simplifies the code.

catch(IOException | FileNotFoundException e)
{
System.out.println(e);
}
Throws/Throw Keywords
 If a method does not handle a checked exception, the method must
declare it using the throws keyword.
 The throws keyword appears at the end of a method's signature.
 You can throw an exception, either a newly instantiated one or an
exception that you just caught, by using the throw keyword.
 throws is used to postpone the handling of a checked exception
 throw is used to invoke an exception explicitly.

--------------------------------------------------------------------------------
The Finally Block
The finally block follows a try block or a catch block.

A finally block of code always executes, irrespective of occurrence of an


Exception.

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

Syntax:
try
{
// Protected code
}
catch(ExceptionType1 e1) {}
catch(ExceptionType2 e2) {}
finally
{
// The finally block always executes.
}
Example:
public class demo
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println(a[3]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println( e);
}
finally
{
a[0] = 6;
System.out.println("First element value: "+a[0]);
System.out.println("Finally statement is executed");
}
}
}

O/P

java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
Finally statement is executed

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy