0% found this document useful (0 votes)
240 views41 pages

Java Exception Handling

The document discusses exception handling in Java. It defines exceptions as unexpected events that disrupt normal program execution. There are two main types of exceptions - checked exceptions which are verified at compile-time, and unchecked exceptions which are verified at runtime. The try-catch block is used to handle exceptions, with the try block containing code that might throw exceptions, and catch blocks handling specific exception types. If an exception is not caught, the default exception handler prints the exception name and stack trace.

Uploaded by

Aparna EV
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
240 views41 pages

Java Exception Handling

The document discusses exception handling in Java. It defines exceptions as unexpected events that disrupt normal program execution. There are two main types of exceptions - checked exceptions which are verified at compile-time, and unchecked exceptions which are verified at runtime. The try-catch block is used to handle exceptions, with the try block containing code that might throw exceptions, and catch blocks handling specific exception types. If an exception is not caught, the default exception handler prints the exception name and stack trace.

Uploaded by

Aparna EV
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 41

JAVA EXCEPTION HANDLING

Introduction
• Exceptions are events that arise due to the occurrence of
unexpected behavior in certain statements, disrupting the
normal execution of a program.
Exceptions examples,
ArrayIndexOfBoundException
ArithmeticException
FileNotFoundException
IOException
NullPointerException
• Whenever an exception occurs in a method, the runtime environment
identifies the type of exception and throws the object of it.
• If the method does not employ any exception handling mechanism, then the
exception is passed to the caller method.
• If no exception handling mechanism is employed in any call stack methods,
the runtime environment passes the exception object to the default
exception handler.
• The default handler prints the name of the exception followed by stack
trace.
Note: stack trace is record of active stack frames generated by the execution of
a program.
When to use Exception Handling
• Common examples are out-of-range array indices, arithmetic overflow
(i.e., a value outside the representable range of values), division by
zero, invalid method parameters, thread interruption and unsuccessful
memory allocation (due to lack of memory).

• Exception handling is not designed to process problems associated with


asynchronous events (e.g., disk I/O completions, network message
arrivals, mouse clicks and keystrokes), which occur in parallel with and
independent of, the program’s flow of control.
class demo {
Public static void main(String args[])
{
Method1( ); }
static void method1()
{
System.out.println(“in method 1, calling method 2”);
In method 1, calling method 2
Method2();
In method 2, calling method 3
System.out.println(“returned from method 2”); }
In method 3
static void method2()
Exception in thread “main”
{
java.lang.ArithmeticException: /by
System.out.println(“in method 2, calling method 3”);
zero
Method3(); at Demo.method2(demo.java:23)
System.out.println(“returned from method 3”); } at Demo.method2(demo.java:16)
Static void method3() at Demo.method2(demo.java:5)
{
System.out.println(“in method 3”);
int a=10, b=0;
int c=a/b;
System.out.println(“method 3 exits”;
}}
Exception Hierarchy
Java.lang.throwable

Error Exception

NoSuchField NoSuchMethod Instantiation RuntimeEx


Exception Exception Exception ception

AssertionE IoError
rror IndexOutOf NullPointerE ArithmeticExce
BpoundExce xception
ption
ption

StringIndexOutOf ArrayIndexOutOfBoun
BoundEceptioj dException
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error
is considered as the unchecked exception. According to Oracle, there are three types
of exceptions:
– Checked Exception
– Unchecked Exception
– Error
1) Checked Exception
The classes which directly inherit 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 which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception Types
Checked Exceptions Unchecked Exceptions

-ClassNotFoundException -ArrayIndexOutOfBoundException
-NoSuchFileException
-ArithmeticException
-NoSuchMethodException
-FileNotFoundException
-InterruptedException

-IOException -IOException
-IllegalAccessException -NullPointerException
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Stack trace
Java try-catch
Java try block
 Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
 Java try block must be followed by either catch or finally block.
Java catch block
 java catch block is used to handle the Exception.
 It must be used after the try block only.
 Multiple catch block can be included for single try
try{
//code that may throw exception }
Catch(Exception_class_Nameref) { }

Problem without exception handling


public class Testtrycatch1{
public static void main(String args[]){ OUTPUT:
int data=50/0;//may throw exception Exception in thread main
System.out.println("rest of the code..."); java.lang.ArithmeticExceptio
}
n:/ by zero
}
• Solution by exception handling
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
OUTPUT:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Internal working of java try-catch 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 exception is handled by the application programmer, normal flow of the
application is maintained i.e. rest of the code is executed.
class demo {
Public static void main(String args[])
{
Method1( ); }
static void method1()
{
System.out.println(“in method 1, calling method 2”);
Method2();
System.out.println(“returned from method 2”); } In method 1, calling method 2
static void method2() In method 2, calling method 3
{
System.out.println(“in method 2, calling method 3”); In method 3
try { Exception Handled
Method3();} Returned from method 3
Catch(Exception e) Returned from method 2
{
System.out.println(“Exception Handled”); }
System.out.println(“returned from method 3”); }
Static void method3()
{
System.out.println(“in method 3”);
int a=10, b=0;
int c=a/b;
}}
Multiple catch clause
• A single try can have multiple catch clauses, for catching specific
exceptions
• As soon as an exception is thrown, the first appropriate catch clause
is located and the exception is passed to it.

try
{
// Protected code
}
catch(ExceptionType1 e1)
{ // Catch block }
catch(ExceptionType2 e2)
{ // Catch block }
catch(ExceptionType3 e3)
{ // Catch block }
class demo {
Public static void main(String args[])
{ In method 1, calling method 2
Method1( ); } In method 2, calling method 3
static void method1() In method 3
{
System.out.println(“in method 1, calling method 2”); Arithmetic Exception Handled :
Method2(); java.lang.ArithmeicException:/
System.out.println(“returned from method 2”); } by zero
static void method2() Returned from method 3
{ Returned from method 2
System.out.println(“in method 2, calling method 3”);
try {
Method3();}
Catch(ArithmeticException ae) Note:
{ All catch blocks must be ordered
System.out.println(“ Arithmetic Exception Handled”, + ae); } from most specific to most general
Catch(Exception e)
{System.out.println(“Exception Handled”); }
i.e. catch for ArithmeticException
System.out.println(“returned from method 3”); } must come before catch for
Static void method3() Exception .
{
System.out.println(“in method 3”); For example : this order of catch
int a=10, b=0;
int c=a/b;
block will produce an compilation
System.out.println(“method 3 exits”); error
}} catch (exception e){ }
Catch( ArithmeticEception ae)
Java Nested try block
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.

Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
Java throw exception
• Java throw keyword
 The Java throw keyword is used to explicitly throw an exception.
 We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
Syntax
throw exception;
throw new IOException("sorry device error”);
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Throws keyword
• 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.

• The throws is added to the method signature

ie. This clause appears after the method’s parameter list and before the method’s body.

• It contains a comma-separated list of the exceptions that the method will throw if various
problems occur.

• Such exceptions may be thrown by statements in the method’s body or by methods


called from the body.

Note:

the difference between throws and throw keywords, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.
class demo { When a=4 b=2
Public static void main(String args[]) In method 1, calling method 2
{
Method1( ); }
In method 2, calling method 3
static void method1() In method 3
{ Result =2
System.out.println(“in method 1, calling method 2”); Returned from method 3
Method2(); Returned from method 2
System.out.println(“returned from method 2”); }
static void method2()
{
System.out.println(“in method 2, calling method 3”);
try { When a=4 b=0
Method3(4,0);} In method 1, calling method 2
Catch(Exception e)
{System.out.println(“Exception Handled”, + e); }
In method 2, calling method 3
System.out.println(“returned from method 3”); } In method 3
Static void method3(int a, int b) throws Exception Exception handled:
{ java.lang.ArithmeticException:
System.out.println(“in method 3”); Testing Throw
If(b==0)
throw new ArithmeticException(“testing Throw”);
Returned from method 3
Else Returned from method 2
System.out.println(“Result: ” + a/b);
}}
Finally Block
• The finally block (which consists of the finally keyword, followed
by code enclosed in curly braces), sometimes referred to as the
finally clause, is optional.
• 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 almost always executes, it typically contains resource-release
code. Suppose a resource is allocated in a try block. If no exception occurs, the
catch blocks are skipped and control proceeds to the finally block, which frees
the resource.
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.
}
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
public class ExcepTest
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println("Access element three :" + a[3]); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
Finally
{
a[0] = 6; System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
} Exception Thrown: java.lang.ArrayIndexOutOfBoundException :3
} First Element value: 6
The Finally statement is executed
Note:

• A catch clause cannot exist without a try statement.

• It is not compulsory to have finally clauses whenever a


try/catch block is present.

• The try block cannot be present without either catch clause or


finally clause.

• Any code cannot be present in between the try, catch, finally


blocks.
Try with resource statement
• Try-with-resources, also referred as automatic resource management, is a new
exception handling mechanism that was introduced in Java 7, which automatically closes
the resources used within the try catch block.
• To use this statement, declare the required resources within the parenthesis, and the
created resource will be closed automatically at the end of the block. Following is the
syntax of try-with-resources statement.
Try(resources to be used and automatically released
{
//statement within the block
}
Example:
try(abc a=new abc(); pqr p= new pqr())
{
//statement within the block
}
Note:

• To use a class with try-with-resources statement it should


implement AutoCloseable interface and the close()method of it gets invoked
automatically at runtime.

• You can declare more than one class in try-with-resources statement.

• While you declare multiple classes in the try block of try-with-resources statement
these classes are closed in reverse order.

• Except the declaration of resources within the parenthesis everything is the same as
normal try/catch block of a try block.

• The resource declared in try gets instantiated just before the start of the try-block.

• The resource declared at the try block is implicitly declared as final.


Class abc implements autocloseable
{
public void close()
{
System.out.println(“within close method of abc”)
}
Class pqr implements autocloseable
{
public void close()
{
System.out.println(“within close method of pqr”) within try with resources block
} within close method of pqr
} within close method of abc
Class TestTryWithResources
{ within catch block
Public static void main()
{
try(abc a=new abc(); pqr p= new pqr())
{
System.out.println(“within try with resources block”);
throw new Exception();
}
Catch(Exception e)
{
System.out.println(“within catch block”)
}
}
}
Note: it is not mandatory for try with resource block to have a catch or finally block.
Multi catch
A single catch block can have multiple exception
types
Syntax:
try
{
//statements
}
catch(Exception 1 | Exception 2 |Exception 3)
{
//statements
}
• The benefit of using multi catch is that it results in efficient
byte code.
• While using multi catch syntax, instanceof operator is used.
Instanceof operator checks whether an instance is of a
particular class and return true or false.

Catch( ArithmeticException | ArrayIndexOfBoundException | NumberFormatException)


{
if( e instanceof ArithmeticException)
System.out.println(“Arithmetic Exception Handled” +e);
Else if (e instanceof NumberFormatException)
System.out.println(“NumberFormatException handled” + e);
Else
System.out.println(e);
}
User Defined Exceptions
• User can create own exceptions in Java. The mandatory
requirement is
-All exceptions must be a child of Throwable.
-If you want to write a checked exception that is
automatically enforced by the Handle or Declare Rule, you
need to extend the Exception class.
-If you want to write a runtime exception, you need to
extend the RuntimeException class.
Syntax:
class MyException extends Exception { }
\\File Name InsufficientFundsException.java import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
// File Name CheckingAccount.
java import java.io.*;
public class CheckingAccount
{ private double balance;
private int number;
public CheckingAccount(int number)
{ this.number = number; }
public void deposit(double amount)
{ balance += amount; }
public void withdraw(double amount) throws InsufficientFundsException
{
if(amount <= balance)
{ balance -= amount; }
else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number; } }
/ File Name BankDemo.
java public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing
$500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00); }
catch(InsufficientFundsException e)
{ System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}}
Output:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
Assertions
• When implementing and debugging a class, it’s sometimes
useful to state conditions that should be true at a particular
point in a method. These conditions, called assertions
• It ensures a program’s validity by catching potential bugs and
identifying possible logic errors during development.
• Preconditions and postconditions are two types of assertions.
• Preconditions
-are assertions about its state when a method is invoked,

• postconditions
-assertions about a program’s state after a method finishes.
• Assertions are boolean expressions that are used to test/validate the code.
• Basically used during testing and development phases
• The first form of the assert statement is
assert expression
which throws an AssertionError if expression is false
 The second form is
assert expression1 : expression2;
which evaluates expression1 and throws an AssertionError
with expression2 as the error message if expression1 is false.
Assertion have to be enabled explicitly: they are disabled by
default. We can enable and disable assertions by
-ea enable assertion
-da disable assertion
• Class assertdemo
static void check(int i)
{
assert i>0: “value must be positive”;
System.out.println(“valu fine” +i);
}
Public static void main(String[] args)
{
Check (Integer.parseInt(args[0]));
}
}
• Output\
when i=1
Java –ea AssertDemo 1
Value fine 1
When i=-1
Java –ea AssertDemo -1
Exception in thread “main” java.lang.Assertionerroe:
value must be positive
At AssertDemo.check(AssertDemo.java:4)
At AssertDemo.main(AssertDemo.java:9)
Without Enabling Assertions
Java AssertDemo -1
Value fine 1

You might also like