SlideShare a Scribd company logo
Exception
Handling in Java
Minal Maniar,
Assistant Professor,
CSPIT, CHARUSAT, Changa
Introduction
• A program can fail for just about any reason. Here are just a few
possibilities:
• The code tries to connect to a website, but the Internet connection is down.
• You made a coding mistake and tried to access an invalid index in an array.
• One method calls another with a value that the method doesn’t support.
• The code tries to connect to a website, but the power goes off.
• You are trying to create an object of some class, Class Not Found
• You try to read from a File, File Not Found
• The code tries to connect to database, database is not available, connection
failed….
Introduction
• Some of these are coding mistakes. Others are completely beyond
your control.
• Your program can’t help it if the Internet connection goes down.
What it can do is deal with the situation.
• Happy path, Unhappy path
• When Java was a kid…
• These are the two approaches Java uses when dealing with
exceptions. A method can handle the exception case itself or make it
the caller’s responsibility.
The Role of Exceptions
Example
When we can use Exceptions?
• Exceptions can and do occur all the time, even in solid program code.
• When you write more advanced programs, you’ll need to deal with
failures in accessing files, networks, and outside services.
• Exceptions are used when “something goes wrong.”
• Exception while Search not found – return a special value
• An exception should be reserved for exceptional conditions like
names being null.
• An exception forces the program to deal with them or end.
• With the exception if left unhandled, whereas a return code could be
accidentally ignored and cause problems later in the program.
• An exception is like shouting, “Deal with me!”
Without Exception handling
• Consider statements in flow
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs - statements 6 to 9 will not get executed
statement 6;
statement 7;
Statement 8;
Statement 9;
Without Exception handling
Without Exception handling
Without Exception handling
After Handling Exceptions
• The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.- Smooth Termination
• Exception is an event that alters program flow.
• Consider statements in flow
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; // If we perform exception handling - statements 6 to 9 will get executed
statement 6;
statement 7;
Statement 8;
Statement 9;
Categories of Exceptions
Understanding Exception Types
Understanding Exception Types: Error
• Error means something went so horribly wrong that your program
should not attempt to recover from it.
• These are exceptional conditions that are external to the application,
and that the application usually cannot anticipate or recover from.
• Ex. suppose that an application successfully opens a file for input, but
is unable to read the file because of a hardware or system
malfunction.
• The unsuccessful read will throw java.io.IOError.
• Errors are not subject to the Catch or Specify Requirement. Errors are
those exceptions indicated by Error and its subclasses.
Exception Types: Runtime Exception
• These are exceptional conditions that are internal to the application, and
that the application usually cannot anticipate or recover from.
• These usually indicate programming bugs, such as logic errors or improper
use of an API.
• Ex1: consider the application described previously that passes a file name
to the constructor for FileReader. If a logic error causes a null to be passed
to the constructor, the constructor will throw NullPointerException.
• The application can catch this exception, but it probably makes more sense
to eliminate the bug that caused the exception to occur.
• Runtime exceptions tend to be unexpected but not necessarily fatal.
• Ex2: accessing an invalid array index is unexpected.
• Runtime exception is defined as the RuntimeException class and its
subclasses.
Exception Types: Unchecked Exception
Understanding Exception Types
• A checked exception includes Exception and all subclasses that do not extend
RuntimeException.
• Checked exceptions tend to be more anticipated—for example, trying to read a
file that doesn’t exist.
• Checked exceptions are checked at compile-time.
• Java has a rule called the handle or declare rule.
• For checked exceptions, Java requires the code to either handle them or declare
them in the method signature.
• For example, this method declares that it might throw an exception:
void fall() throws Exception {
throw new Exception();
}
Checked Exception
• These are exceptional conditions that a well-written application should
anticipate and recover from.
• For example, suppose an application prompts a user for an input file name,
then opens the file by passing the name to the constructor for
java.io.FileReader. Normally, the user provides the name of an existing,
readable file, so the construction of the FileReader object succeeds, and
the execution of the application proceeds normally. But sometimes the
user supplies the name of a nonexistent file, and the constructor throws
java.io.FileNotFoundException. A well-written program will catch this
exception and notify the user of the mistake, possibly prompting for a
corrected file name.
• Checked exceptions are subject to the Catch or Specify Requirement. All
exceptions are checked exceptions, except for those indicated by Error,
RuntimeException, and their subclasses.
Examples
• Examples of a Runtime exception
• NullPointerException
• ArrayIndexOutOfBoundsException
• StringIndexOutOfBoundsException
• ArithmeticException
• NumberFormatException
• Checked Exception examples:
• FileNotFoundException
• SQLException
Java Exception Handling Keywords
try catch finally throw throws
The try block
The first step in constructing an exception handler is to enclose the
code that might throw an exception within a try block. In general, a try
block looks like the following:
try {
code
}
catch and finally blocks . . .
What happens when an Exception is thrown?
• When an error occurs within a method, the method creates an object
and hands it off to the runtime system.
• The object, called an exception object, contains information about the
1. Error, including its type and
2. The state of the program when the error occurred.
Creating an exception object and handing it to the
runtime system is called throwing an exception.
The call stack
After a method throws an
exception, the runtime
system attempts to find
something to handle it.
The set of possible
"somethings" to handle
the exception is the
ordered list of methods
that had been called to get
to the method where the
error occurred. The list of
methods is known as
the call stack.
Method where error occurred
Method without an exception
handler
Method with an exception
handler
main
Method call
Method call
Method call
Searching the call stack for the exception handler
Method where error occurred
Method without an exception
handler
Method with an exception
handler
main
Looking for
appropriate
handler
Looking for
appropriate
handler
Throws Exception
Frorward Exception
Catches some other
Exception
Searching the call stack for the exception
handler
• The runtime system searches the call stack for a method that contains a
block of code that can handle the exception. This block of code is called
an exception handler. The search begins with the method in which the
error occurred and proceeds through the call stack in the reverse order in
which the methods were called. When an appropriate handler is found, the
runtime system passes the exception to the handler. An exception handler
is considered appropriate if the type of the exception object thrown
matches the type that can be handled by the handler.
• The exception handler chosen is said to catch the exception. If the runtime
system exhaustively searches all the methods on the call stack without
finding an appropriate exception handler, as shown in the next figure, the
runtime system (and, consequently, the program) terminates.
How to handle exception?
• We must use one of these pairs to handle the exception...
1. try - catch - [ similar to if else]
2. try - catch- finally
3. Try – multiple catch - finally
4. try - finally
i=0,
Income/0
Creates object of Exception,
search for catch block
Prints Exception type and
information
Executes finally block
Skips
execution
till catch
found
Resumes with rest of
the code after finally
1
Exception Handling call flow - 1
• Output
Whichever exception occurs,
that matching catch block is
executed
Finally block gets executed
Rest of the code gets executed
after finally
Rest of the code gets executed
out of outer try block
Outer finally block gets
executed
2
Exception Handling call flow -2
• Output
Exception occurred, but no matching
catch block found
Finally block gets executed
Skipped
Rest of the code gets executed
Exception caught here
In case No matching catch block found in
inner try, nearest matching block is – Outer
catch block
Executes finally block of
outer try
3
Exception Handling call flow - 3
• Output
Exception caught here
Finally block gets executed
Outer Finally block
gets executed
4
Exception Handling call flow - 4
• Output
“the finally block always runs after the catch block”
Program gets terminated at Line no 10
5
Exception Handling call flow - 5
• Output
Use of finally block
• The finally block always executes when the try block exits.
• This ensures that the finally block is executed even if an unexpected
exception occurs.
• But finally is useful for more than just exception handling — it allows
the programmer to avoid having cleanup code accidentally bypassed
by a return, continue, or break. Putting cleanup code in a finally block
is always a good practice, even when no exceptions are anticipated.
• Note: If the JVM exits while the try or catch code is being executed,
then the finally block may not execute. Likewise, if the thread
executing the try or catch code is interrupted or killed, the finally
block may not execute even though the application as a whole
continues.
Use of finally block
• The runtime system always executes the statements within the finally block
regardless of what happens within the try block. So it's the perfect place to
perform cleanup.
• The following finally block for the method cleans up and then closes the
PrintWriter.
• The finally block is a key tool for preventing resource leaks. When closing a file or
otherwise recovering resources, place the code in a finally block to ensure that
resource is always recovered.
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
The try-with-resources Statement
• Consider using the try-with-resources statement in these situations, which
automatically releases system resources when no longer needed.
1. static String readFirstLineFromFile(String path) throws IOException {
2. try (BufferedReader br = new BufferedReader(new FileReader(path))) {
3. return br.readLine();
4. }
5. }
• This example reads the first line from a file. It uses an instance of
BufferedReader to read data from the file. BufferedReader is a resource
that must be closed after the program is finished with it.
The try-with-finally Statement
• Prior to Java SE 7, you can use a finally block to ensure that a resource is closed
regardless of whether the try statement completes normally or abruptly. The following
example uses a finally block instead of a try-with-resources statement:
1. static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
2. BufferedReader br = new BufferedReader(new FileReader(path));
3. try {
4. return br.readLine();
5. } finally {
6. if (br != null) br.close();
7. }
8. }
Throwing an Exception
• The throw keyword tells Java you want some other part of the code to
deal with the exception.
1. throw new Exception();
2. throw new Exception("Ow! I fell.");
• Above examples create a new object of type Exception and throw it.
• The Java throw keyword is used to explicitly throw an exception.
• We can throw either checked or unchecked exception.
• It is s mainly used to throw custom exception.
Specifying the Exceptions Thrown by a Method
using “throws” keyword
• To specify or to declare that method can throw exceptions, add a throws
clause to the method declaration for the that method.
• The throws clause comprises the throws keyword followed by a comma-
separated list of all the exceptions thrown by that method. The clause goes
after the method name and argument list and before the brace that defines
the scope of the method; here's an example.
public void writeList() throws IOException, IndexOutOfBoundsException {..}
• Here, IndexOutOfBoundsException is an unchecked exception; including it
in the throws clause is not mandatory.
• You could just write the following.
public void writeList() throws IOException {..}
Declare Exception
throw Exception
throw and throws example
• Output
See other examples of throw exception in Exception.txt file
Declare multiple exceptions separated by comma
You can declare multiple
Exceptions in method
signature
Catching More Than One Type of Exception
with One Exception Handler
• In Java 7, catch block has been improved to handle multiple
exceptions in a single catch block. If you are catching multiple
exceptions and they have similar code, then using this feature will
reduce code duplication.
• In the catch clause, specify the types of exceptions that block can
handle, and separate each exception type with a vertical bar (|):
Types of exceptions
Chained Exceptions
• Exception handlers can do more than just print error messages or halt the
program. They can do error recovery, prompt the user to make a decision,
or propagate the error up to a higher-level handler using chained
exceptions.
• Throwing an exception along with another exception forms a chained
exception.
• In the preceding section, the catch block rethrows the original exception.
Sometimes, you may need to throw a new exception (with additional
information) along with the original exception.
• This is called chained exceptions.
• See example in next slide.
method2() is called from method1()
throws Exception
Catch block of caller
method gets executed
Catch block of caller
method gets executed
Chained Exceptions
• Output
Defining Custom Exception Classes
• You can define a custom exception class by extending the
java.lang.Exception class.
• Java provides quite a few exception classes. Use them whenever
possible instead of defining your own exception classes. However, if
you run into a problem that cannot be adequately described by the
predefined exception classes, you can create your own exception
class, derived from Exception or from a subclass of Exception, such as
IOException.
Custom Exceptions
• Output
Exception Handling with MethodOverriding in
Java
• There are many rules if we talk about methodoverriding with
exception handling.
• If the superclass method does not declare an exception
• If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
• If the superclass method declares an exception
• If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare
parent exception.
If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.
Compilation Error
If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but can declare unchecked exception.
Output:
child
If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
Output:
Compilation error
Subclass overridden method can declares same
exception – this is valid
Example in case subclass overridden method declares subclass exception
Advantages of Exceptions
• https://docs.oracle.com/javase/tutorial/essential/exceptions/advanta
ges.html
References
• http://www.geeksforgeeks.org
• Introduction to Java Programming, Comprehensive Version (10th
Edition), Y. Daniel Liang
• https://docs.oracle.com/javase/tutorial/essential/exceptions/advanta
ges.html
• https://www.javatpoint.com
• https://www.journaldev.com
• OCA Oracle Certified Associate Java SE 8 Programmer Study Guide
Exam 1Z0 808

More Related Content

What's hot

Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Java review: try catch
Java review: try catchJava review: try catch
Java review: try catch
Muzahidul Islam
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
Java2Blog
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
QaziUmarF786
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
Minal Maniar
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 
Java8 features
Java8 featuresJava8 features
Java8 features
Minal Maniar
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practicesAngelin R
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
rithustutorials
 

What's hot (20)

Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Java review: try catch
Java review: try catchJava review: try catch
Java review: try catch
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
 
Java exception
Java exception Java exception
Java exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 

Similar to Exception handling

Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
EXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograamingEXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograaming
MuskanNazeer
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
thenmozhip8
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Kavitha713564
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
Waheed Warraich
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptionsSujit Kumar
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Exception Handling in UiPath.pptx
Exception Handling in UiPath.pptxException Handling in UiPath.pptx
Exception Handling in UiPath.pptx
ApurbaSamanta9
 
Design byexceptions
Design byexceptionsDesign byexceptions
Design byexceptionsAsif Tasleem
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
JAYESHRODGE
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 

Similar to Exception handling (20)

Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
EXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograamingEXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograaming
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
 
Exception
ExceptionException
Exception
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exception Handling in UiPath.pptx
Exception Handling in UiPath.pptxException Handling in UiPath.pptx
Exception Handling in UiPath.pptx
 
Design byexceptions
Design byexceptionsDesign byexceptions
Design byexceptions
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

More from Minal Maniar

Java ce241
Java ce241Java ce241
Java ce241
Minal Maniar
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
Io
IoIo
Class method object
Class method objectClass method object
Class method object
Minal Maniar
 
Object oriented thinking
Object oriented thinkingObject oriented thinking
Object oriented thinking
Minal Maniar
 
2 class use case
2 class use case2 class use case
2 class use case
Minal Maniar
 
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
1 modeling concepts
1 modeling concepts1 modeling concepts
1 modeling concepts
Minal Maniar
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
4 sdlc
4 sdlc4 sdlc
4 sdlc
Minal Maniar
 
3 interaction and_state_modeling
3 interaction and_state_modeling3 interaction and_state_modeling
3 interaction and_state_modeling
Minal Maniar
 
modeling concepts
modeling conceptsmodeling concepts
modeling concepts
Minal Maniar
 

More from Minal Maniar (13)

Java ce241
Java ce241Java ce241
Java ce241
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Io
IoIo
Io
 
Class method object
Class method objectClass method object
Class method object
 
Object oriented thinking
Object oriented thinkingObject oriented thinking
Object oriented thinking
 
2 class use case
2 class use case2 class use case
2 class use case
 
Oop java
Oop javaOop java
Oop java
 
1 modeling concepts
1 modeling concepts1 modeling concepts
1 modeling concepts
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
4 sdlc
4 sdlc4 sdlc
4 sdlc
 
3 interaction and_state_modeling
3 interaction and_state_modeling3 interaction and_state_modeling
3 interaction and_state_modeling
 
modeling concepts
modeling conceptsmodeling concepts
modeling concepts
 
modeling concepts
modeling conceptsmodeling concepts
modeling concepts
 

Recently uploaded

space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 

Recently uploaded (20)

space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 

Exception handling

  • 1. Exception Handling in Java Minal Maniar, Assistant Professor, CSPIT, CHARUSAT, Changa
  • 2. Introduction • A program can fail for just about any reason. Here are just a few possibilities: • The code tries to connect to a website, but the Internet connection is down. • You made a coding mistake and tried to access an invalid index in an array. • One method calls another with a value that the method doesn’t support. • The code tries to connect to a website, but the power goes off. • You are trying to create an object of some class, Class Not Found • You try to read from a File, File Not Found • The code tries to connect to database, database is not available, connection failed….
  • 3. Introduction • Some of these are coding mistakes. Others are completely beyond your control. • Your program can’t help it if the Internet connection goes down. What it can do is deal with the situation. • Happy path, Unhappy path • When Java was a kid… • These are the two approaches Java uses when dealing with exceptions. A method can handle the exception case itself or make it the caller’s responsibility.
  • 4. The Role of Exceptions
  • 6. When we can use Exceptions? • Exceptions can and do occur all the time, even in solid program code. • When you write more advanced programs, you’ll need to deal with failures in accessing files, networks, and outside services. • Exceptions are used when “something goes wrong.” • Exception while Search not found – return a special value • An exception should be reserved for exceptional conditions like names being null. • An exception forces the program to deal with them or end. • With the exception if left unhandled, whereas a return code could be accidentally ignored and cause problems later in the program. • An exception is like shouting, “Deal with me!”
  • 7. Without Exception handling • Consider statements in flow statement 1; statement 2; statement 3; statement 4; statement 5; //exception occurs - statements 6 to 9 will not get executed statement 6; statement 7; Statement 8; Statement 9;
  • 11. After Handling Exceptions • The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.- Smooth Termination • Exception is an event that alters program flow. • Consider statements in flow statement 1; statement 2; statement 3; statement 4; statement 5; // If we perform exception handling - statements 6 to 9 will get executed statement 6; statement 7; Statement 8; Statement 9;
  • 14. Understanding Exception Types: Error • Error means something went so horribly wrong that your program should not attempt to recover from it. • These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. • Ex. suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. • The unsuccessful read will throw java.io.IOError. • Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.
  • 15. Exception Types: Runtime Exception • These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. • These usually indicate programming bugs, such as logic errors or improper use of an API. • Ex1: consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. • The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur. • Runtime exceptions tend to be unexpected but not necessarily fatal. • Ex2: accessing an invalid array index is unexpected. • Runtime exception is defined as the RuntimeException class and its subclasses.
  • 17. Understanding Exception Types • A checked exception includes Exception and all subclasses that do not extend RuntimeException. • Checked exceptions tend to be more anticipated—for example, trying to read a file that doesn’t exist. • Checked exceptions are checked at compile-time. • Java has a rule called the handle or declare rule. • For checked exceptions, Java requires the code to either handle them or declare them in the method signature. • For example, this method declares that it might throw an exception: void fall() throws Exception { throw new Exception(); }
  • 18. Checked Exception • These are exceptional conditions that a well-written application should anticipate and recover from. • For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name. • Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
  • 19. Examples • Examples of a Runtime exception • NullPointerException • ArrayIndexOutOfBoundsException • StringIndexOutOfBoundsException • ArithmeticException • NumberFormatException • Checked Exception examples: • FileNotFoundException • SQLException
  • 20. Java Exception Handling Keywords try catch finally throw throws
  • 21. The try block The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following: try { code } catch and finally blocks . . .
  • 22. What happens when an Exception is thrown? • When an error occurs within a method, the method creates an object and hands it off to the runtime system. • The object, called an exception object, contains information about the 1. Error, including its type and 2. The state of the program when the error occurred.
  • 23. Creating an exception object and handing it to the runtime system is called throwing an exception.
  • 24. The call stack After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack. Method where error occurred Method without an exception handler Method with an exception handler main Method call Method call Method call
  • 25. Searching the call stack for the exception handler Method where error occurred Method without an exception handler Method with an exception handler main Looking for appropriate handler Looking for appropriate handler Throws Exception Frorward Exception Catches some other Exception
  • 26. Searching the call stack for the exception handler • The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. • The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.
  • 27. How to handle exception? • We must use one of these pairs to handle the exception... 1. try - catch - [ similar to if else] 2. try - catch- finally 3. Try – multiple catch - finally 4. try - finally
  • 28. i=0, Income/0 Creates object of Exception, search for catch block Prints Exception type and information Executes finally block Skips execution till catch found Resumes with rest of the code after finally 1
  • 29. Exception Handling call flow - 1 • Output
  • 30. Whichever exception occurs, that matching catch block is executed Finally block gets executed Rest of the code gets executed after finally Rest of the code gets executed out of outer try block Outer finally block gets executed 2
  • 31. Exception Handling call flow -2 • Output
  • 32. Exception occurred, but no matching catch block found Finally block gets executed Skipped Rest of the code gets executed Exception caught here In case No matching catch block found in inner try, nearest matching block is – Outer catch block Executes finally block of outer try 3
  • 33. Exception Handling call flow - 3 • Output
  • 34. Exception caught here Finally block gets executed Outer Finally block gets executed 4
  • 35. Exception Handling call flow - 4 • Output “the finally block always runs after the catch block”
  • 36. Program gets terminated at Line no 10 5
  • 37. Exception Handling call flow - 5 • Output
  • 38. Use of finally block • The finally block always executes when the try block exits. • This ensures that the finally block is executed even if an unexpected exception occurs. • But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. • Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
  • 39. Use of finally block • The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup. • The following finally block for the method cleans up and then closes the PrintWriter. • The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered. finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } }
  • 40. The try-with-resources Statement • Consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed. 1. static String readFirstLineFromFile(String path) throws IOException { 2. try (BufferedReader br = new BufferedReader(new FileReader(path))) { 3. return br.readLine(); 4. } 5. } • This example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it.
  • 41. The try-with-finally Statement • Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement: 1. static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { 2. BufferedReader br = new BufferedReader(new FileReader(path)); 3. try { 4. return br.readLine(); 5. } finally { 6. if (br != null) br.close(); 7. } 8. }
  • 42. Throwing an Exception • The throw keyword tells Java you want some other part of the code to deal with the exception. 1. throw new Exception(); 2. throw new Exception("Ow! I fell."); • Above examples create a new object of type Exception and throw it. • The Java throw keyword is used to explicitly throw an exception. • We can throw either checked or unchecked exception. • It is s mainly used to throw custom exception.
  • 43. Specifying the Exceptions Thrown by a Method using “throws” keyword • To specify or to declare that method can throw exceptions, add a throws clause to the method declaration for the that method. • The throws clause comprises the throws keyword followed by a comma- separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method; here's an example. public void writeList() throws IOException, IndexOutOfBoundsException {..} • Here, IndexOutOfBoundsException is an unchecked exception; including it in the throws clause is not mandatory. • You could just write the following. public void writeList() throws IOException {..}
  • 45. throw and throws example • Output See other examples of throw exception in Exception.txt file
  • 46. Declare multiple exceptions separated by comma You can declare multiple Exceptions in method signature
  • 47. Catching More Than One Type of Exception with One Exception Handler • In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication. • In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|):
  • 49. Chained Exceptions • Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions. • Throwing an exception along with another exception forms a chained exception. • In the preceding section, the catch block rethrows the original exception. Sometimes, you may need to throw a new exception (with additional information) along with the original exception. • This is called chained exceptions. • See example in next slide.
  • 50. method2() is called from method1() throws Exception Catch block of caller method gets executed Catch block of caller method gets executed
  • 52. Defining Custom Exception Classes • You can define a custom exception class by extending the java.lang.Exception class. • Java provides quite a few exception classes. Use them whenever possible instead of defining your own exception classes. However, if you run into a problem that cannot be adequately described by the predefined exception classes, you can create your own exception class, derived from Exception or from a subclass of Exception, such as IOException.
  • 53.
  • 55. Exception Handling with MethodOverriding in Java • There are many rules if we talk about methodoverriding with exception handling. • If the superclass method does not declare an exception • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception. • If the superclass method declares an exception • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
  • 56. If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception. Compilation Error
  • 57. If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception. Output: child
  • 58. If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. Output: Compilation error Subclass overridden method can declares same exception – this is valid
  • 59. Example in case subclass overridden method declares subclass exception
  • 60. Advantages of Exceptions • https://docs.oracle.com/javase/tutorial/essential/exceptions/advanta ges.html
  • 61. References • http://www.geeksforgeeks.org • Introduction to Java Programming, Comprehensive Version (10th Edition), Y. Daniel Liang • https://docs.oracle.com/javase/tutorial/essential/exceptions/advanta ges.html • https://www.javatpoint.com • https://www.journaldev.com • OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1Z0 808