SlideShare a Scribd company logo
CHAPTER 5 EXCEPTION HANDLING
By
Sirage Zeynu (M.Tech)
School of Computing
13-04-2021 Exception handling 2
Outlines
1.Exception handling overview
2.The causes of exceptions
3.The Throwable class hierarchy
4.Handling of an exception
5.The throw statements
6.The finally clause
13-04-2021 Exception handling 3
 An exception is an indication of a problem that occurs during a
program’s execution.
 An exception is a runtime error.
 The name “exception” implies that the problem occurs
infrequently - if the “rule” is that a statement normally executes
correctly, and then the “exception to the rule” is that a problem
occurs.
 When an exception occurs, the normal execution flow of the
program will be interrupted.
 Exception handling enables you to create applications that can
resolve (or handle) exceptions.
Exception Handling Overview(1)
13-04-2021 Exception handling 4
 In many cases, handling an exception allows a program to
continue executing as if no problem had been encountered.
 A more severe problem could prevent a program from
continuing normal execution, instead requiring it to notify the
user of the problem before terminating in a controlled manner.
 Exceptions occur for various reasons.
Exception Handling Overview(2)
13-04-2021 Exception handling 5
 The user may enter an invalid input, for example, or the
program may attempt to open a file that doesn't exist, or the
network connection may hang up, or the program may
attempt to access an out-of-bounds array element.
 Exception handling – resolving exceptions that may occur so
program can continue or terminate gracefully
 Exception handling enables programmers to create programs
that are more robust and fault-tolerant
Exception Handling Overview(3)
13-04-2021 Exception handling 6
Here is an example. The program shown below terminates
abnormally if you enter a floating-point value instead of an
integer.
13-04-2021 Exception handling 7
 If 12.5 is entered for the integer variable, the program will terminate
unexpectedly by generating the exception shown below.
Note that several lines of information are displayed above in response to the
invalid input.
This information, known as the stack trace, includes the name of the
exception (java.util.InputMismatchException) followed by the method call
stack at the time the exception occurred.
13-04-2021 Exception handling 8
 The stack trace helps in debugging a program.
 Starting from the last line of the stack trace, you see that the
exception was detected in line 9 of the main method.
 Each line of the stack trace contains the class name and method
(ExceptionDemo.main) along with the file name and line number
(ExceptionDemo.java: 9).
 Moving up the stack trace, you see that the exception occurred in
line 1485 in the nextInt method of the Scanner class, the exception
occurred in line 2117 in the overloaded nextInt method of the
Scanner class, the exception occurred in line 2076 in the next
method of the Scanner class, the exception occurred in line 864 in
the throwFor method of the Scanner class.
13-04-2021 Exception handling 9
But the following program reports an error message if 12.5 is entered for the
integer variable and the program continues normally executing after displaying
the error message.
13-04-2021 Exception handling 10
 A Java exception is an instance of a class derived from
Throwable.
 The Throwable class is contained in the java.lang package, and
subclasses of Throwable are contained in various packages.
 Errors related to GUI components are included in the java.awt
package; numeric exceptions are included in the java.lang
package because they are related to the java.lang.Number
class.
 You can create your own exception classes by extending
Throwable or a subclass of Throwable. Figure below shows
some of Java's predefined exception classes.
Exceptions and Exception Types
11
Exception Classes
13-04-2021 Exception handling 12
System errors are thrown by
JVM and represented in the
Error class. The Error class
describes internal system
errors. Such errors rarely
occur. If one does, there is
little you can do beyond
notifying the user and trying
to terminate the program
gracefully.
System Errors
13-04-2021 Exception handling 13
Exception describes errors
caused by your program
and external circumstances.
These errors can be caught
and handled by your
program.
Exceptions
13-04-2021 Exception handling 14
Runtime Exceptions
13-04-2021 Exception handling 15
 Errors are thrown by the JVM and represented in the Error class.
 Errors are not caused due to user program.
 The Error class describes internal system errors. Such errors rarely
occur.
 If one does, there is little you can do beyond notifying the user and
trying to terminate the program gracefully.
 Errors that result from program activity are represented by
subcasses of Exception.
 Exceptions are represented in the Exception class, which describes
errors caused by your program and by external circumstances.
 These errors can be caught and handled by your program.
13-04-2021 Exception handling 16
ClassNotFoundE
xception
Attempt to use a class that does not exist. This exception would occur, for
example, if you tried to run a nonexistent class using the java command, or if
your program was composed of, say, three class files, only two of which
could be found.
IOException Related to input/output operations, such as invalid input, reading
past the end of a file, and opening a nonexistent file. Examples of
subclasses of IOException are InterruptedIOException,
EOFException (EOF is short for End Of File), and FileNotFound
Exception.
AWTException Exceptions in GUI components
Examples of subclasses of Exception
13-04-2021 Exception handling 17
 Runtime exceptions are represented in the RuntimeException
class, which describes programming errors, such as bad
casting, accessing an out-of-bounds array, and numeric errors.
Runtime exceptions are generally thrown by the JVM.
 Examples of subclasses are shown below.
Runtime exceptions
13-04-2021 Exception handling 18
ArithmeticException Dividing an integer by zero. Note that
floating-point arithmetic does not throw
exceptions.
NullPointerException Attempt to access an object through a null
reference variable.
IndexOutOfBoundsException Index to an array is out of range.
IllegalArgumentException A method is passed an argument that is
illegal or inappropriate.
13-04-2021 Exception handling 19
 RuntimeException, Error, and their subclasses are known as
unchecked exceptions.
 All other exceptions are known as checked exceptions, meaning
that the compiler forces the programmer to check and deal with
them.
 In most cases, unchecked exceptions reflect programming logic
errors that are not recoverable.
 For example, a NullPointerException is thrown if you access an
object through a reference variable before an object is assigned to
it; an IndexOutOfBoundsException is thrown if you access an
element in an array outside the bounds of the array.
 These are logic errors that should be corrected in the program.
13-04-2021 Exception handling 20
13-04-2021 Exception handling 21
difference between checked and unchecked exception
 The main difference between checked and unchecked
exception is that the checked exceptions are checked at
compile-time while unchecked exceptions are checked at run-
time.
What are checked exceptions?
 Checked exceptions are checked at compile-time. It means if a
method is throwing a checked exception then it should handle
the exception using try-catch block or it should declare the
exception using throws keyword, otherwise the program will
give a compilation error.
13-04-2021 Exception handling 22
What are Unchecked exceptions?
 Unchecked exceptions are not checked at compile time. It
means if your program is throwing an unchecked exception
and even if you didn’t handle/declare that exception, the
program won’t give a compilation error.
 Most of the times these exception occurs due to the bad data
provided by user during the user-program interaction.
 It is up to the programmer 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.
13-04-2021 Exception handling 23
 Java exception handling is managed via 5 keywords:
try, catch, throw, throws and finally.
 Program statements that you want to monitor for exceptions are
contained within a try block.
 If an exception occurs within a try block, it is thrown. Your code
can catch this exception using catch and handle it.
 System-generated exceptions are automatically thrown by java
run-time system.
 To manually throw an exception, use the keyword throw.
13-04-2021 Exception handling 24
 The try block contains set of statements where an exception
can occur.
 A try block is always followed by a catch block, which
handles the exception that occurs in associated try block. A
try block must be followed by catch blocks or finally block or
both.
Syntax of try block
try{
//statements that may cause an exception
}
try block
13-04-2021 Exception handling 25
 A catch block is where you handle the exceptions, this block
must follow the try block.
 A single try block can have several catch blocks associated
with it.
 You can catch different exceptions in different catch blocks.
 When an exception occurs in try block, the corresponding
catch block that handles that particular exception executes.
 For example if an arithmetic exception occurs in try block then
the statements enclosed in catch block for arithmetic
exception executes.
Catch block
13-04-2021 Exception handling 26
Using try and catch
General form of try/catch:
13-04-2021 Exception handling 27
Example: try catch block
13-04-2021 Exception handling 28
 Lets see few rules about multiple catch blocks with the help of examples.
 1. single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions.
 ArrayIndexOutOfBoundsException or
 ArithmeticException or
 NullPointerException or
 any other type of exception
 3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can handle ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException
5. You can also throw exception, which is an advanced topic
Multiple catch blocks in Java
13-04-2021 Exception handling 29
Example of Multiple catch blocks
13-04-2021 Exception handling 30
 A finally block contains all the crucial statements that must be executed
whether exception occurs or not.
 The statements present in this block will always execute regardless of whether
exception occurs in try block or not such as closing a connection, stream etc.
syntax of Finally block
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
Finally block
13-04-2021 Exception handling 31
A Simple Example of finally block
13-04-2021 Exception handling 32
 exception object is an object of class java.lang.Exception or
some subclass of it.
 When JVM encounters a throw statement, it stops executing
the block in which the throw occurs and will not execute any
additional code in the program unless it encounters a proper
catch statement.
 throw exception object ;
Throw keyword
13-04-2021 Exception handling 33
Throw Example
13-04-2021 Exception handling 34
Throws keyword is used for handling checked exceptions .
By using throws we can declare multiple exceptions in one go.
 What is the need of having throws keyword when you can
handle exception using try-catch?
The throws does the same thing that try-catch does but there are
some cases where you would prefer throws over try-catch.
 For example:
Lets say we have a method myMethod() that has statements that
can throw either ArithmeticException or NullPointerException,
in this case you can use try-catch as shown below:
Throws key word in java
13-04-2021 Exception handling 35
public void myMethod() {
try
{
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
} }
13-04-2021 Exception handling 36
public void myMethod() throws ArithmeticException, NullPointerException
{
// Statements that might throw an exception
}
public static void main(String args[]) {
try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}}
13-04-2021 Exception handling 37
Throws Example
13-04-2021 Exception handling 38
Example of throws Keyword
13-04-2021 Exception handling 39
1. Throws clause is used to declare an exception, which means it works
similar to the try-catch block. On the other hand throw keyword is used to
throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance of Exception
class and throws is followed by exception class names.
For example:
throw new ArithmeticException("Arithmetic Exception");
and
throws ArithmeticException;
3. Throw keyword is used in the method body to throw an exception, while
throws is used in method signature to declare the exceptions that can occur in
the statements present in the method.
4. You can throw one exception at a time but you can handle multiple
exceptions by declaring them using throws keyword.
Throw vs Throws in java
13-04-2021 Exception handling 40
For example:
Throw:
void myMethod()
{
//Throwing single exception using throw
throw new ArithmeticException("An integer should not be divided by
zero!!");
}
Throws:
//Declaring multiple exceptions using throws
void myMethod() throws ArithmeticException, NullPointerException
{
//Statements where exception might occur
}
13-04-2021 Introduction to Java and OO Concepts 41

More Related Content

What's hot

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Chapter13 exception handling
Chapter13 exception handlingChapter13 exception handling
Chapter13 exception handling
Prabhakar Nallabolu
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event HandlingJava Programming
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
TharuniDiddekunta
 
Operators, control statements represented in java
Operators, control statements  represented in javaOperators, control statements  represented in java
Operators, control statements represented in java
TharuniDiddekunta
 
How to handle exceptions in Java Technology
How to handle exceptions in Java Technology How to handle exceptions in Java Technology
How to handle exceptions in Java Technology
Prognoz Technologies Pvt. Ltd.
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Kavitha713564
 
Exception handling
Exception handlingException handling
Exception handling
Sandeep Rawat
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ravinderkaur165
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Ferdin Joe John Joseph PhD
 

What's hot (18)

Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Chapter13 exception handling
Chapter13 exception handlingChapter13 exception handling
Chapter13 exception handling
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Operators, control statements represented in java
Operators, control statements  represented in javaOperators, control statements  represented in java
Operators, control statements represented in java
 
How to handle exceptions in Java Technology
How to handle exceptions in Java Technology How to handle exceptions in Java Technology
How to handle exceptions in Java Technology
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

Similar to Chapter 5

UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Types of Exceptionsfsfsfsdfsdfdsfsfsdfsd
Types of ExceptionsfsfsfsdfsdfdsfsfsdfsdTypes of Exceptionsfsfsfsdfsdfdsfsfsdfsd
Types of Exceptionsfsfsfsdfsdfdsfsfsdfsd
ssuserce9e9d
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
DrRajeshreeKhande
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
Swabhav Techlabs
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 

Similar to Chapter 5 (20)

UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
 
Types of Exceptionsfsfsfsdfsdfdsfsfsdfsd
Types of ExceptionsfsfsfsdfsdfdsfsfsdfsdTypes of Exceptionsfsfsfsdfsdfdsfsfsdfsd
Types of Exceptionsfsfsfsdfsdfdsfsfsdfsd
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java exception
Java exception Java exception
Java exception
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Unit 5 Java
Unit 5 JavaUnit 5 Java
Unit 5 Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 

More from siragezeynu

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
siragezeynu
 
6 database
6 database 6 database
6 database
siragezeynu
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
siragezeynu
 
Chapter one
Chapter oneChapter one
Chapter one
siragezeynu
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
siragezeynu
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
siragezeynu
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
siragezeynu
 
Lab4
Lab4Lab4
Chapter 6
Chapter 6Chapter 6
Chapter 6
siragezeynu
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
siragezeynu
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
siragezeynu
 
6 chapter 6 record storage and primary file organization
6 chapter 6  record storage and primary file organization6 chapter 6  record storage and primary file organization
6 chapter 6 record storage and primary file organization
siragezeynu
 

More from siragezeynu (12)

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
6 database
6 database 6 database
6 database
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
 
Chapter one
Chapter oneChapter one
Chapter one
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
 
Lab4
Lab4Lab4
Lab4
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
6 chapter 6 record storage and primary file organization
6 chapter 6  record storage and primary file organization6 chapter 6  record storage and primary file organization
6 chapter 6 record storage and primary file organization
 

Recently uploaded

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 

Chapter 5

  • 1. CHAPTER 5 EXCEPTION HANDLING By Sirage Zeynu (M.Tech) School of Computing
  • 2. 13-04-2021 Exception handling 2 Outlines 1.Exception handling overview 2.The causes of exceptions 3.The Throwable class hierarchy 4.Handling of an exception 5.The throw statements 6.The finally clause
  • 3. 13-04-2021 Exception handling 3  An exception is an indication of a problem that occurs during a program’s execution.  An exception is a runtime error.  The name “exception” implies that the problem occurs infrequently - if the “rule” is that a statement normally executes correctly, and then the “exception to the rule” is that a problem occurs.  When an exception occurs, the normal execution flow of the program will be interrupted.  Exception handling enables you to create applications that can resolve (or handle) exceptions. Exception Handling Overview(1)
  • 4. 13-04-2021 Exception handling 4  In many cases, handling an exception allows a program to continue executing as if no problem had been encountered.  A more severe problem could prevent a program from continuing normal execution, instead requiring it to notify the user of the problem before terminating in a controlled manner.  Exceptions occur for various reasons. Exception Handling Overview(2)
  • 5. 13-04-2021 Exception handling 5  The user may enter an invalid input, for example, or the program may attempt to open a file that doesn't exist, or the network connection may hang up, or the program may attempt to access an out-of-bounds array element.  Exception handling – resolving exceptions that may occur so program can continue or terminate gracefully  Exception handling enables programmers to create programs that are more robust and fault-tolerant Exception Handling Overview(3)
  • 6. 13-04-2021 Exception handling 6 Here is an example. The program shown below terminates abnormally if you enter a floating-point value instead of an integer.
  • 7. 13-04-2021 Exception handling 7  If 12.5 is entered for the integer variable, the program will terminate unexpectedly by generating the exception shown below. Note that several lines of information are displayed above in response to the invalid input. This information, known as the stack trace, includes the name of the exception (java.util.InputMismatchException) followed by the method call stack at the time the exception occurred.
  • 8. 13-04-2021 Exception handling 8  The stack trace helps in debugging a program.  Starting from the last line of the stack trace, you see that the exception was detected in line 9 of the main method.  Each line of the stack trace contains the class name and method (ExceptionDemo.main) along with the file name and line number (ExceptionDemo.java: 9).  Moving up the stack trace, you see that the exception occurred in line 1485 in the nextInt method of the Scanner class, the exception occurred in line 2117 in the overloaded nextInt method of the Scanner class, the exception occurred in line 2076 in the next method of the Scanner class, the exception occurred in line 864 in the throwFor method of the Scanner class.
  • 9. 13-04-2021 Exception handling 9 But the following program reports an error message if 12.5 is entered for the integer variable and the program continues normally executing after displaying the error message.
  • 10. 13-04-2021 Exception handling 10  A Java exception is an instance of a class derived from Throwable.  The Throwable class is contained in the java.lang package, and subclasses of Throwable are contained in various packages.  Errors related to GUI components are included in the java.awt package; numeric exceptions are included in the java.lang package because they are related to the java.lang.Number class.  You can create your own exception classes by extending Throwable or a subclass of Throwable. Figure below shows some of Java's predefined exception classes. Exceptions and Exception Types
  • 12. 13-04-2021 Exception handling 12 System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. System Errors
  • 13. 13-04-2021 Exception handling 13 Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. Exceptions
  • 14. 13-04-2021 Exception handling 14 Runtime Exceptions
  • 15. 13-04-2021 Exception handling 15  Errors are thrown by the JVM and represented in the Error class.  Errors are not caused due to user program.  The Error class describes internal system errors. Such errors rarely occur.  If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.  Errors that result from program activity are represented by subcasses of Exception.  Exceptions are represented in the Exception class, which describes errors caused by your program and by external circumstances.  These errors can be caught and handled by your program.
  • 16. 13-04-2021 Exception handling 16 ClassNotFoundE xception Attempt to use a class that does not exist. This exception would occur, for example, if you tried to run a nonexistent class using the java command, or if your program was composed of, say, three class files, only two of which could be found. IOException Related to input/output operations, such as invalid input, reading past the end of a file, and opening a nonexistent file. Examples of subclasses of IOException are InterruptedIOException, EOFException (EOF is short for End Of File), and FileNotFound Exception. AWTException Exceptions in GUI components Examples of subclasses of Exception
  • 17. 13-04-2021 Exception handling 17  Runtime exceptions are represented in the RuntimeException class, which describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Runtime exceptions are generally thrown by the JVM.  Examples of subclasses are shown below. Runtime exceptions
  • 18. 13-04-2021 Exception handling 18 ArithmeticException Dividing an integer by zero. Note that floating-point arithmetic does not throw exceptions. NullPointerException Attempt to access an object through a null reference variable. IndexOutOfBoundsException Index to an array is out of range. IllegalArgumentException A method is passed an argument that is illegal or inappropriate.
  • 19. 13-04-2021 Exception handling 19  RuntimeException, Error, and their subclasses are known as unchecked exceptions.  All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with them.  In most cases, unchecked exceptions reflect programming logic errors that are not recoverable.  For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array.  These are logic errors that should be corrected in the program.
  • 21. 13-04-2021 Exception handling 21 difference between checked and unchecked exception  The main difference between checked and unchecked exception is that the checked exceptions are checked at compile-time while unchecked exceptions are checked at run- time. What are checked exceptions?  Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error.
  • 22. 13-04-2021 Exception handling 22 What are Unchecked exceptions?  Unchecked exceptions are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error.  Most of the times these exception occurs due to the bad data provided by user during the user-program interaction.  It is up to the programmer 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.
  • 23. 13-04-2021 Exception handling 23  Java exception handling is managed via 5 keywords: try, catch, throw, throws and finally.  Program statements that you want to monitor for exceptions are contained within a try block.  If an exception occurs within a try block, it is thrown. Your code can catch this exception using catch and handle it.  System-generated exceptions are automatically thrown by java run-time system.  To manually throw an exception, use the keyword throw.
  • 24. 13-04-2021 Exception handling 24  The try block contains set of statements where an exception can occur.  A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both. Syntax of try block try{ //statements that may cause an exception } try block
  • 25. 13-04-2021 Exception handling 25  A catch block is where you handle the exceptions, this block must follow the try block.  A single try block can have several catch blocks associated with it.  You can catch different exceptions in different catch blocks.  When an exception occurs in try block, the corresponding catch block that handles that particular exception executes.  For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes. Catch block
  • 26. 13-04-2021 Exception handling 26 Using try and catch General form of try/catch:
  • 27. 13-04-2021 Exception handling 27 Example: try catch block
  • 28. 13-04-2021 Exception handling 28  Lets see few rules about multiple catch blocks with the help of examples.  1. single try block can have any number of catch blocks. 2. A generic catch block can handle all the exceptions.  ArrayIndexOutOfBoundsException or  ArithmeticException or  NullPointerException or  any other type of exception  3. If no exception occurs in try block then the catch blocks are completely ignored. 4. Corresponding catch blocks execute for that specific type of exception: catch(ArithmeticException e) is a catch block that can handle ArithmeticException catch(NullPointerException e) is a catch block that can handle NullPointerException 5. You can also throw exception, which is an advanced topic Multiple catch blocks in Java
  • 29. 13-04-2021 Exception handling 29 Example of Multiple catch blocks
  • 30. 13-04-2021 Exception handling 30  A finally block contains all the crucial statements that must be executed whether exception occurs or not.  The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc. syntax of Finally block try { //Statements that may cause an exception } catch { //Handling exception } finally { //Statements to be executed } Finally block
  • 31. 13-04-2021 Exception handling 31 A Simple Example of finally block
  • 32. 13-04-2021 Exception handling 32  exception object is an object of class java.lang.Exception or some subclass of it.  When JVM encounters a throw statement, it stops executing the block in which the throw occurs and will not execute any additional code in the program unless it encounters a proper catch statement.  throw exception object ; Throw keyword
  • 33. 13-04-2021 Exception handling 33 Throw Example
  • 34. 13-04-2021 Exception handling 34 Throws keyword is used for handling checked exceptions . By using throws we can declare multiple exceptions in one go.  What is the need of having throws keyword when you can handle exception using try-catch? The throws does the same thing that try-catch does but there are some cases where you would prefer throws over try-catch.  For example: Lets say we have a method myMethod() that has statements that can throw either ArithmeticException or NullPointerException, in this case you can use try-catch as shown below: Throws key word in java
  • 35. 13-04-2021 Exception handling 35 public void myMethod() { try { // Statements that might throw an exception } catch (ArithmeticException e) { // Exception handling statements } catch (NullPointerException e) { // Exception handling statements } }
  • 36. 13-04-2021 Exception handling 36 public void myMethod() throws ArithmeticException, NullPointerException { // Statements that might throw an exception } public static void main(String args[]) { try { myMethod(); } catch (ArithmeticException e) { // Exception handling statements } catch (NullPointerException e) { // Exception handling statements }}
  • 37. 13-04-2021 Exception handling 37 Throws Example
  • 38. 13-04-2021 Exception handling 38 Example of throws Keyword
  • 39. 13-04-2021 Exception handling 39 1. Throws clause is used to declare an exception, which means it works similar to the try-catch block. On the other hand throw keyword is used to throw an exception explicitly. 2. If we see syntax wise than throw is followed by an instance of Exception class and throws is followed by exception class names. For example: throw new ArithmeticException("Arithmetic Exception"); and throws ArithmeticException; 3. Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method. 4. You can throw one exception at a time but you can handle multiple exceptions by declaring them using throws keyword. Throw vs Throws in java
  • 40. 13-04-2021 Exception handling 40 For example: Throw: void myMethod() { //Throwing single exception using throw throw new ArithmeticException("An integer should not be divided by zero!!"); } Throws: //Declaring multiple exceptions using throws void myMethod() throws ArithmeticException, NullPointerException { //Statements where exception might occur }
  • 41. 13-04-2021 Introduction to Java and OO Concepts 41

Editor's Notes

  1. If an exception occurs in try block then the control of execution is passed to the corresponding catch block. A single try block can have multiple catch blocks associated with it, you should place the catch blocks in such a way that the generic exception handler catch block is at the last(see in the example below). The generic exception handler can handle all the exceptions but you should place is at the end, if you place it at the before all the catch blocks then it will display the generic message. You always want to give the user a meaningful message for each type of exception rather then a generic message.
  2. If you are wondering why we need other catch handlers when we have a generic that can handle all. This is because in generic exception handler you can display a message but you are not sure for which type of exception it may trigger so it will display the same message for all the exceptions and user may not be able to understand which exception occurred. Thats the reason you should place is at the end of all the specific exception catch blocks
  3. Out put Warning: ArithmeticException Out of try-catch block… .In the above example there are multiple catch blocks and these catch blocks executes sequentially when an exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it can handle all exceptions. This catch block should be placed at the last to avoid such situations.
  4. Output: Number should not be divided by zero This is finally block Out of try-catch-finally Few Important points regarding finally block 1. A finally block must be associated with a try block, you cannot use finally without a try block. You should place those statements in this block that must be executed always. 2. Finally block is optional, a try-catch block is sufficient for exception handling, however if you place a finally block then it will always run after the execution of try block. 3. In normal case when there is no exception in try block then the finally block is executed after try block. However if an exception occurs then the catch block is executed before finally block. 4. An exception in the finally block, behaves exactly like any other exception. 5. The statements present in the finally block execute even if the try block contains control transfer statements like return, break or continue. Lets see an example to see how finally works when return statement is present in try block:
  5. Output: Exception in thread "main" java.lang.ArithmeticException: Not Eligible for voting at Example1.checkAge(Example1.java:4) at Example1.main(Example1.java:10)
  6. But suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable. One way to overcome this problem is by using throws like this: declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch. Another advantage of using this approach is that you will be forced to handle the exception when you call this method, all the exceptions that are declared using throws, must be handled where you are calling this method else you will get compilation error.
  7. Output: You shouldn't divide number by zero
  8. Output: java.io.IOException: IOException Occurred