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

Unit3 First Half

The document provides an overview of exception handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details the hierarchy of exception classes, types of exceptions (checked and unchecked), and the use of keywords such as try, catch, finally, throw, and throws. Additionally, it includes examples and scenarios illustrating common exceptions and how to handle them effectively.

Uploaded by

anuja.it
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit3 First Half

The document provides an overview of exception handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details the hierarchy of exception classes, types of exceptions (checked and unchecked), and the use of keywords such as try, catch, finally, throw, and throws. Additionally, it includes examples and scenarios illustrating common exceptions and how to handle them effectively.

Uploaded by

anuja.it
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Exception Handling

• The Exception Handling in Java is one of the


powerful mechanism to handle the runtime errors so that
the normal flow of the application can be maintained.
Exception:
• Definition:1
• A Java exception is an object that describes an exceptional
(that is, error) condition that has occurred in a piece of code.
• Definition:2
• In Java, an 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 ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
• Advantage of Exception Handling
• The core advantage of exception handling is to
maintain the normal flow of the application. An
exception normally disrupts the normal flow of the
application; that is why we need to handle
exceptions.
Let's consider a scenario
Suppose there are 10
• statement 1; statements in a Java
• statement 2; program and an exception
occurs at statement 5; the
• statement 3; rest of the code will not be
executed, i.e., statements
• statement 4; 6 to 10 will not be
• executed. However, when
statement 5;//exception occurs we perform exception
• statement 6; handling, the rest of the
statements will be
• statement 7; executed. That is why we
use exception handling in
• statement 8; Java
• statement 9;
• statement 10;
Hierarchy of Java Exception classes
• All exception types are subclasses of the built-in class Throwable. Thus,
Throwable is at the top of the exception class hierarchy. Immediately below
Throwable are two subclasses that partition exceptions into two distinct
branches.
• One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. This is also the class that you will
subclass to create your own custom exception types.
• There is an important subclass of Exception, called RuntimeException.
Exceptions of this type are automatically defined for the programs that you
write and include things such as division by zero and invalid array indexing.
• The other branch is topped by Error, which defines exceptions that are not
expected to be caught under normal circumstances by your program.
Exceptions of type Error are used by the Java run-time system to indicate
errors having to do with the run-time environment, itself. Stack overflow is an
example of such an error.
Types of Java Exceptions

• There are mainly two types of exceptions:


checked and unchecked. An error is
considered as the unchecked exception.
• Checked Exception
• Unchecked Exception
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.
Java Exception Keywords

try
• The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch or
finally.
catch
• The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
finally
• The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throw
• The "throw" keyword is used to throw an exception.
throws
• The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with
method signature.
Java Exception Handling Example

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
} Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
} rest of the code...
Common Scenarios of Java Exceptions

There are given some scenarios where


unchecked exceptions may occur. They are as
follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an
ArithmeticException.
int a=50/0;//ArithmeticException
2) 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
• 3) 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
4) A scenario where
ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the
ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur
ArrayIndexOutOfBoundsException. Consider the
following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java try block

• Java try block is used to enclose the code that


might throw an exception. It must be used
within the method.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Java catch block

• Java catch block is used to handle the


Exception by declaring the type of exception
within the parameter. The declared exception
must be the parent class exception ( i.e.,
Exception) or the generated exception type.
• The catch block must be used after the try
block only. You can use multiple catch block
with a single try block
• The JVM firstly checks whether the exception is handled
or not. If exception is not handled, JVM provides a default
exception handler that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the
exception occurred).
• Causes the program to terminate.
• But if the application programmer handles the exception,
the normal flow of the application is maintained, i.e., rest
of the code is executed.
Problem without exception handling

public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

System.out.println("rest of the code");

Output:
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
Solution by exception handling
Example1

public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
Output:
} java.lang.ArithmeticException: / by zero
rest of the code
Example2
public class TryCatchExample9 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} Output:
java.lang.ArrayIndexOutOfBoundsException: 10
} rest of the code
Java Multi-catch block

• A try block can be followed by one or more catch blocks.


Each catch block must contain a different exception
handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch
block.
• Points to remember
• At a time only one exception occurs and at a time only
one catch block is executed.
• All catch blocks must be ordered from most specific to
most general, i.e. catch for ArithmeticException must
come before catch for Exception.
Flowchart of Multi-catch Block
Example 1
MultipleCatchBlock1.java
public class MultipleCatchBlock1 { catch(Exception e)
{
public static void main(String[] args) { System.out.println("Parent E
occurs");
try{ }
int a[]=new int[5]; System.out.println("rest of the
a[5]=30/0; } }
} Output:
catch(ArithmeticException e) Arithmetic Exception occursrest of the
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
Example 2

public class MultipleCatchBlock2 {


public static void main(String[] args) {

try{
int a[]=new int[5];
Output:
System.out.println(a[10]); ArrayIndexOutOfBounds Exception occurs
} rest of the code
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Example 3

• In this example, we generate


NullPointerException, but didn't provide the
corresponding exception type. In such case,
the catch block containing the parent
exception class Exception will invoked.
Example 3
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{ Output:
String s=null; Parent Exception occurs
System.out.println(s.length());
rest of the code
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java Nested try block

• In Java, using a try block inside another try


block is permitted. It is called as nested try
block. Every statement that we enter a
statement in try block, context of that
exception is pushed onto the stack.
• For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException whil
e the outer try block can handle
the ArithemeticException (division by zero).
Why use nested try block

• Sometimes a situation may arise where a part


of a block may cause one error and the entire
block itself may cause another error. In such
cases, exception handlers have to be nested
try Syntax
{ statement 1;
statement 2;
//try catch block within another try block
try
{ statement 3;
statement 4;
//try catch block within nested try block
try
{ statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
} }
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
NestedTryBlock.java

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}
Output:
• When any try block does not have a catch block for
a particular exception, then the catch block of the
outer (parent) try block are checked for that
exception, and if it matches, the catch block of
outer try block is executed.
• If none of the catch block specified in the code is
unable to handle the exception, then the Java
runtime system will handle the exception. Then it
displays the system generated message for that
exception
Java finally block

• Java finally block is a block used to execute


important code such as closing the
connection, etc.
• Java finally block is always executed whether
an exception is handled or not. Therefore, it
contains all the necessary statements that
need to be printed regardless of the exception
occurs or not
Why use Java finally block?

• finally block in Java can be used to put


"cleanup" code such as closing a file, closing
connection, etc.
• The important statements to be printed can
be placed in the finally block.
When an exception occurs and is handled
by the catch block
public class TestFinallyBlock2{
public static void main(String args[]){
try {
System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Java throw Exception

• The Java throw keyword is used to throw an


exception explicitly.
• We specify the exception object which is to be
thrown. The Exception has some message
with it that provides the error description.
• We can throw either checked or unchecked
exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.
syntax
throw Instance
i.e.,
throw new exception_class("error message");
Throwing Unchecked Exception
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Java throws keyword

• The Java throws keyword is used to declare


an exception. It gives an information to the
programmer that there may occur an
exception. So, it is better for the programmer
to provide the exception handling code so that
the normal flow of the program can be
maintained.
Syntax of Java throws

return_type method_name() throws exception_


class_name
{
//method code
}
Which exception should be declared?

Ans: Checked exception only, because:


• unchecked exception: under our control so we
can correct our code.
• error: beyond our control. For example, we
are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword

• It provides information to the caller of the


method about the exception.
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}
Output
Exception in thread "main"
java.lang.ArithmeticException: Access denied -
You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
} }
exception handled
normal flow...
Differences between throw and throws.
Java Built-in Exception

• Inside the standard package java.lang, Java defines several


exception classes. The most general of these exceptions are
subclasses of the standard type RuntimeException
• In the language of Java, these are called unchecked exceptions
because the compiler does not check to see if a method
handles or throws these exceptions.
• The unchecked exceptions defined in java.lang are listed in
Table 10-1.
• Table 10-2 lists those exceptions defined by java.lang that
must be included in a method’s throws list if that method can
generate one of these exceptions and does not handle it itself.
These are called checked exceptions
unchecked exceptions
Checked Exception
Java Custom Exception/User Defined Exception

• In Java, we can create our own exceptions that


are derived classes of the Exception class.
• In order to create custom exception, we need
to extend Exception class that belongs to
java.lang package.
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}
Output
Example 2
class EmployeeException extends Exception
{
public EmployeeException(String s) Output
{
Exception caught
super(s);
Invalid Employee ID
}}
class SampleEmp
{
void empIDCheck(int EmpID) throws EmployeeException{
if(EmpID<=0 || EmpID>999){
throw new EmployeeException("Invalid Employee ID");
}}
public static void main(String args[])
{
SampleEmp emp = new SampleEmp();
try
{
emp.empIDCheck(0);
}
catch (EmployeeException e)
{
System.out.println("Exception caught");
System.out.println(e.getMessage());
}}}

You might also like