SlideShare a Scribd company logo
1
Java Exception Handling
Copyrights, All rights reserved.
All details provided in this slide is only for personal
learning, and cannot be distributed publicly, without
written permission of the Author.
Contact milogik652@gmail.com to Learn Core Java
and any other Java related Technologies
Contents
1. What is an Exception?
2. Purpose of Exceptions
3. Exception Keywords
4. Exception Control Flow
5. Inbuilt Exceptions
6. Exceptions in other Packages/Frameworks
7. Order of Catching Exceptions
8. Nested Exceptions
9. Exception class Hierarchy
10.Checked & Unchecked Exceptions
11.User Defined Checked Exceptions
12.User Defined Unchecked Exceptions
Contact milogik652@gmail.com to Learn Core Java,
Spring, Spring Boot, Hibernate, Microservices or any
other Java related Technologies
1. What is an Exception?
An Exception is run time problem or error which
occurs, when program is under execution.
An Exception may occur due to Environment, bad
programming, or due to unexpected input data.
For example:
When you access an array element which is beyond
the range of array, an
java.lang.ArrayIndexOutOfBoundsException is
thrown.
In C Language there is no built in Exception handling,
developer need to manually write the code to check
the range, using multiple if statements, which clutters
the code.Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
What is an Exception?
Car Wheel
broken on run,
An exception
handler avoids
crashing/overtu
rn/accident of
car, and slows
down in next
few meters
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
2. Purpose of Exceptions?
1. Exceptions improves User Experience
2. makes the Program more Robust, avoiding Crashes
3. Helps developer by generating basic Exception
Handling code
4. Improves code readability separating Business Logic
and Exception handling code
5. Stack Unwinding
Java has built in support for Exception handling.
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
3. Exception Keywords
Java provides inbuilt Exception Handling as
• 5 keywords
• Few inbuilt classes(Exception related classes)
Below are keywords used in Exception handling
1.try - set of program statements which may throw an
Exception need to be enclosed within try block
2.catch – set of program statements which can handle
Exception scenario need to be enclosed in catch
block. A try block can have multiple catch blocks.
3.throw – throw keyword is used to manually throw an
Exception. Is used in the method body.
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
7
Exception Keywords
Code snippet with try, catch, throw keywords
try
{
//statements
throw new Exception(); //optional
}
catch(Exception e)
{
System.out.println(“Exception occurred”+ e);
}
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
8
4.throws – is used along with method declaration to
specify that a method can throw one or more
Exceptions. Is used with method declaration.
void met() throws AbcException, XyzException;
Exception can be thrown across methods in different
classes, which can be different packages.
5.finally – statements in finally block gets executed
whether are not Exception occurs. Generally releasing
used resources, like closing file, network
connections,etc… need to be done in finally block. finally
block gets executed, before returning from the method ,
in all cases.
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
9
try
{
//statements
}
catch(Exception1 e1)
{
//statements
}
finally
{
//statements
}
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
10
4. Control Flow of Exceptions:
Flow of Execution when Exception Occurs
void met1()
{
//business logic
try{
//business logic
//exception occurred
//when above exception is thrown, these statements does not execute
}
catch(Exception et)
{
//statements in catch block gets executed only if exception occurs
}
}
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
11
Execution Flow when Exception does not occur
void met1()
{
//business logic
try{
//business logic
//full code in try block gets executed if exception is not thrown
}
catch(Exception et)
{
//if exception is not thrown, statements in catch block does not execute
}
finally
{
//statements here always gets executed whether or not Exception occurs
}
} Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
12
try with finally and without catch
As already known finally block can exist only with a try
block, and may be without catch block. since the
Exception is either directly or indirectly thrown from the
statements within try block, and since this Exception is
not being handled within the method, as there is no
catch block.
throws statement may need to be used in method
declaration, however we want some statements to be
always executed(either Exception occurs or not)
before returning this method, such statements need to
be placed in finally block
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
13
void met() throws XyzException
{
//statements here
try{
//statements here
}
finally
{
//statements which need ot be always executed
}
}
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
5. List of some built in Exceptions
Below Exceptions are in java.lang package
There a number of other Exceptions like IOException,
SocketException, etc…
Exception class name Occurs when
NullPointerException referring a Reference which is null
ArrayIndexOutofBoundsException accessing an array element which doesn’t exist(i..e
actual size of array is < index being referred)
NumberFormatException occurs when Integer.parseInt(“10”), and given string
cannot be converted into valid Integer
ArithmeticException dividing by zero
OutofMemoryError Heap memory is full(UnChecked)
StringIndexOutOfBoundsException referring a String index which doesn’t exist
StackOverflowError Stack memory is full, generally occurs due to
nested calls(UnChecked)
14
15
6. Exceptions in other Packages & Frameworks:
Most of commonly used Exceptions exist in default
package(i..e java.lang)
There are a number of Exceptions such as
SQLException(defined in java.sql package),
ConnectException, UnknownHostException(defined in
java.net package)
Similarly there can be a number of Pre defined/Custom
Exceptions which are defined by its own packages or
Framework, for it’s specific purpose, you need to refer
documentation of that specific Framework to know the
purpose of it.
16
7. Order of catching Exceptions
A try block can have zero or more catch blocks.
When a try block has multiple catch blocks, the derived
most Exceptions classes need to be caught first, and
then Base Exception classes need to be caught, else it
leads to Compiler error due to unreachable code.
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
17
Order of catching Exceptions
This applies to Custom Exception classes as well.
try{
//program statements
}
catch(ArrayIndexOutofBoundsException abe)
{
//
}
catch(Exception e)
{
//
} Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
18
8. Nested Exceptions
It is possible to have a try block within another try block.
A catch block can have another try catch blocks
try
{
//stmt 1
try{
//stmt 2
}catch(Exception et){ et.printStackTrace(); }
//stmt 3
}catch(Exception e)
{
e.printStackTrace();
} Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
19
Though the flow of program execution can be controlled
using Exceptions.
Exceptions need to be used only to handle Exception
Scenarios, and should not be used to actually control
flow of execution of program.
java.lang.Exception is base class of all Exception
classes.
Exception class has below methods.
1.printStackTrace()
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
Object
Throwable
Error Exception
RuntimeException
20
9. Exception class Hierarchy
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
21
Difference between Exception and Error classes
The first one catches all subclasses of Throwable (this
includes Exception and Error), the second one catches
all subclasses of Exception.
Error is programmatically unrecoverable in any way and
is usually not to be caught, except for logging purposes
(which passes it through again).
Exception is programmatically recoverable.
Its subclass RuntimeException indicates a programming
error and is not mandatory to be caught.
22
try{
}
catch(Throwable t){}
try{
}catch(Exception e){}
⮚ In Java, exceptions are objects. When you throw an
exception, you throw an object.
⮚ You can't throw just any object as an exception. you can
throw only those objects whose classes descend
from Throwable.
⮚ Throwable serves as the base class for an entire family
of classes, declared in java.lang, that your program can
instantiate and throw.
⮚ Throwable has two direct subclasses, Exception and
Error. 23
10. Exception class Hierarchy
⮚ java.lang.Exception class represents the exceptions
which are mainly caused by the application itself.
⮚ For example, NullPointerException occurs when an
application tries to access null object or
ClassCastException occurs when an application tries to
cast incompatible class types.
⮚ Errors (members of the Error family) are usually thrown for
more serious problems, such as OutOfMemoryError or
StackOverflowError, that may not be so easy to handle.
⮚ In general, code you write should throw only exceptions, not
errors.
⮚ Errors are usually thrown by the methods of the Java API, or
by the Java virtual machine itself, due to environment issues.
24
Exception class Hierarchy
25
Exception class is base class of all Exception classes
eg. ArithmeticException,
NullPointerException,
ArrayIndexOutofBoundsException,etc…
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
26
11. Checked & Unchecked Exceptions
Exceptions are broadly classified into two
1.Checked Exceptions – These are the Exceptions
which are checked by Compiler, and need to be
handled(using try, catch) or thrown(using throws)
explicitly.
All Checked Exceptions are derived from Exception
class
2.UnChecked Exceptions – It is not mandatory to
handle or throw(using throws) Unchecked Exceptions
explicitly.
All Unchecked Exceptions are derived from
RuntimeException class
27
Since forcing a developer to catch each and every
Exception is not a good option, Java provides
UnChecked exceptions. These are the exceptions
which need not be explicitly handled by the developer.
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
28
12. How to create User defined Checked Exception
29
13. How to create user defined UnChecked Exception
30
Thank You!
31
Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot,
Hibernate, Microservices or any other Java related Technologies
Ad

More Related Content

What's hot (20)

Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Exception handling
Exception handlingException handling
Exception handling
Anna Pietras
 
Exception handling
Exception handling Exception handling
Exception handling
M Vishnuvardhan Reddy
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
Ravi Chythanya
 
JDK,JRE,JVM
JDK,JRE,JVMJDK,JRE,JVM
JDK,JRE,JVM
Cognizant
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
Madishetty Prathibha
 
Logging with log4j v1.2
Logging with log4j v1.2Logging with log4j v1.2
Logging with log4j v1.2
Kamal Mettananda
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
myrajendra
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
KrutikaWankhade1
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Java
JavaJava
Java
Tony Nguyen
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 

Similar to Java exception-handling (20)

UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
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
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Kavitha713564
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
TharuniDiddekunta
 
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
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programmingException‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 
Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
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
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Garuda Trainings
 
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
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
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
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Kavitha713564
 
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
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programmingException‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
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
 
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
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Ad

Recently uploaded (20)

Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
Ad

Java exception-handling

  • 1. 1 Java Exception Handling Copyrights, All rights reserved. All details provided in this slide is only for personal learning, and cannot be distributed publicly, without written permission of the Author. Contact milogik652@gmail.com to Learn Core Java and any other Java related Technologies
  • 2. Contents 1. What is an Exception? 2. Purpose of Exceptions 3. Exception Keywords 4. Exception Control Flow 5. Inbuilt Exceptions 6. Exceptions in other Packages/Frameworks 7. Order of Catching Exceptions 8. Nested Exceptions 9. Exception class Hierarchy 10.Checked & Unchecked Exceptions 11.User Defined Checked Exceptions 12.User Defined Unchecked Exceptions Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 3. 1. What is an Exception? An Exception is run time problem or error which occurs, when program is under execution. An Exception may occur due to Environment, bad programming, or due to unexpected input data. For example: When you access an array element which is beyond the range of array, an java.lang.ArrayIndexOutOfBoundsException is thrown. In C Language there is no built in Exception handling, developer need to manually write the code to check the range, using multiple if statements, which clutters the code.Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 4. What is an Exception? Car Wheel broken on run, An exception handler avoids crashing/overtu rn/accident of car, and slows down in next few meters Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 5. 2. Purpose of Exceptions? 1. Exceptions improves User Experience 2. makes the Program more Robust, avoiding Crashes 3. Helps developer by generating basic Exception Handling code 4. Improves code readability separating Business Logic and Exception handling code 5. Stack Unwinding Java has built in support for Exception handling. Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 6. 3. Exception Keywords Java provides inbuilt Exception Handling as • 5 keywords • Few inbuilt classes(Exception related classes) Below are keywords used in Exception handling 1.try - set of program statements which may throw an Exception need to be enclosed within try block 2.catch – set of program statements which can handle Exception scenario need to be enclosed in catch block. A try block can have multiple catch blocks. 3.throw – throw keyword is used to manually throw an Exception. Is used in the method body. Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 7. 7 Exception Keywords Code snippet with try, catch, throw keywords try { //statements throw new Exception(); //optional } catch(Exception e) { System.out.println(“Exception occurred”+ e); } Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 8. 8 4.throws – is used along with method declaration to specify that a method can throw one or more Exceptions. Is used with method declaration. void met() throws AbcException, XyzException; Exception can be thrown across methods in different classes, which can be different packages. 5.finally – statements in finally block gets executed whether are not Exception occurs. Generally releasing used resources, like closing file, network connections,etc… need to be done in finally block. finally block gets executed, before returning from the method , in all cases. Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 9. 9 try { //statements } catch(Exception1 e1) { //statements } finally { //statements } Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 10. 10 4. Control Flow of Exceptions: Flow of Execution when Exception Occurs void met1() { //business logic try{ //business logic //exception occurred //when above exception is thrown, these statements does not execute } catch(Exception et) { //statements in catch block gets executed only if exception occurs } } Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 11. 11 Execution Flow when Exception does not occur void met1() { //business logic try{ //business logic //full code in try block gets executed if exception is not thrown } catch(Exception et) { //if exception is not thrown, statements in catch block does not execute } finally { //statements here always gets executed whether or not Exception occurs } } Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 12. 12 try with finally and without catch As already known finally block can exist only with a try block, and may be without catch block. since the Exception is either directly or indirectly thrown from the statements within try block, and since this Exception is not being handled within the method, as there is no catch block. throws statement may need to be used in method declaration, however we want some statements to be always executed(either Exception occurs or not) before returning this method, such statements need to be placed in finally block Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 13. 13 void met() throws XyzException { //statements here try{ //statements here } finally { //statements which need ot be always executed } } Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 14. 5. List of some built in Exceptions Below Exceptions are in java.lang package There a number of other Exceptions like IOException, SocketException, etc… Exception class name Occurs when NullPointerException referring a Reference which is null ArrayIndexOutofBoundsException accessing an array element which doesn’t exist(i..e actual size of array is < index being referred) NumberFormatException occurs when Integer.parseInt(“10”), and given string cannot be converted into valid Integer ArithmeticException dividing by zero OutofMemoryError Heap memory is full(UnChecked) StringIndexOutOfBoundsException referring a String index which doesn’t exist StackOverflowError Stack memory is full, generally occurs due to nested calls(UnChecked) 14
  • 15. 15 6. Exceptions in other Packages & Frameworks: Most of commonly used Exceptions exist in default package(i..e java.lang) There are a number of Exceptions such as SQLException(defined in java.sql package), ConnectException, UnknownHostException(defined in java.net package) Similarly there can be a number of Pre defined/Custom Exceptions which are defined by its own packages or Framework, for it’s specific purpose, you need to refer documentation of that specific Framework to know the purpose of it.
  • 16. 16 7. Order of catching Exceptions A try block can have zero or more catch blocks. When a try block has multiple catch blocks, the derived most Exceptions classes need to be caught first, and then Base Exception classes need to be caught, else it leads to Compiler error due to unreachable code. Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 17. 17 Order of catching Exceptions This applies to Custom Exception classes as well. try{ //program statements } catch(ArrayIndexOutofBoundsException abe) { // } catch(Exception e) { // } Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 18. 18 8. Nested Exceptions It is possible to have a try block within another try block. A catch block can have another try catch blocks try { //stmt 1 try{ //stmt 2 }catch(Exception et){ et.printStackTrace(); } //stmt 3 }catch(Exception e) { e.printStackTrace(); } Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 19. 19 Though the flow of program execution can be controlled using Exceptions. Exceptions need to be used only to handle Exception Scenarios, and should not be used to actually control flow of execution of program. java.lang.Exception is base class of all Exception classes. Exception class has below methods. 1.printStackTrace() Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 20. Object Throwable Error Exception RuntimeException 20 9. Exception class Hierarchy Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 21. 21 Difference between Exception and Error classes The first one catches all subclasses of Throwable (this includes Exception and Error), the second one catches all subclasses of Exception. Error is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception is programmatically recoverable. Its subclass RuntimeException indicates a programming error and is not mandatory to be caught.
  • 23. ⮚ In Java, exceptions are objects. When you throw an exception, you throw an object. ⮚ You can't throw just any object as an exception. you can throw only those objects whose classes descend from Throwable. ⮚ Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw. ⮚ Throwable has two direct subclasses, Exception and Error. 23 10. Exception class Hierarchy
  • 24. ⮚ java.lang.Exception class represents the exceptions which are mainly caused by the application itself. ⮚ For example, NullPointerException occurs when an application tries to access null object or ClassCastException occurs when an application tries to cast incompatible class types. ⮚ Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError or StackOverflowError, that may not be so easy to handle. ⮚ In general, code you write should throw only exceptions, not errors. ⮚ Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself, due to environment issues. 24 Exception class Hierarchy
  • 25. 25 Exception class is base class of all Exception classes eg. ArithmeticException, NullPointerException, ArrayIndexOutofBoundsException,etc… Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 26. 26 11. Checked & Unchecked Exceptions Exceptions are broadly classified into two 1.Checked Exceptions – These are the Exceptions which are checked by Compiler, and need to be handled(using try, catch) or thrown(using throws) explicitly. All Checked Exceptions are derived from Exception class 2.UnChecked Exceptions – It is not mandatory to handle or throw(using throws) Unchecked Exceptions explicitly. All Unchecked Exceptions are derived from RuntimeException class
  • 27. 27 Since forcing a developer to catch each and every Exception is not a good option, Java provides UnChecked exceptions. These are the exceptions which need not be explicitly handled by the developer. Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  • 28. 28
  • 29. 12. How to create User defined Checked Exception 29
  • 30. 13. How to create user defined UnChecked Exception 30
  • 31. Thank You! 31 Contact milogik652@gmail.com to Learn Core Java, Spring, Spring Boot, Hibernate, Microservices or any other Java related Technologies
  翻译: