SlideShare a Scribd company logo
Introduction To Java Exceptions
Sujit Kumar
Zenolocity LLC © 2013-2023
Exceptions
• Events that disrupt the normal flow of
execution.
• Exception Object
1) cause (can contain another exception),
2) detailed message.
• Can be thrown by the programmer using the
throw keyword.
• Can be caught by the programmer using the
catch keyword.
Benefits of Java Exception Handling
• Cleaner code by separating error handling
code from normal or happy path code.
• Propagate errors up the call stack where they
can be handled meaningfully.
• Helps to categorize exceptions using the
exception hierarchy.
Types of Errors
• JVM Errors => OutOfMemoryError,
StackOverflowError, LinkageError
• System Errors => FileNotFoundException,
IOException, NullPointerException,
ArrayIndexOutOfBoundsException
• Application Errors => InsufficientFundsException
(transfer balance from one account to another).
• JVM & System Errors are built-in, Application
Errors are user defined.
Introduction to java exceptions
Exception Handling – try, catch, finally
• Try block – normal flow of execution.
• Catch blocks ( 1 or more) – exception handling
code, are like if-else-if statements – only 1 can
potentially execute.
• Derived class exception should be caught
before a base class exception in the catch
blocks.
• If an exception is thrown that is not handled,
it is propagated up the call stack.
Finally Block
• Finally block – clean up code, always gets
executed, even when you have a return in
try/catch or any exception is re-thrown.
• When does finally not execute ? – It may not
execute when JVM terminates (via
System.exit()) or current thread is killed or
system runs out of memory.
• If an exception is thrown that is not handled,
it is propagated up the call stack.
Checked & Unchecked Exceptions
• Checked – compiler forces you to either catch
them or declare in the throws clause. Use it
for recoverable errors.
• Unchecked – RuntimeException and its
subclasses are unchecked exceptions. Compiler
does not force you to catch them. Unchecked
exceptions do not need to be declared in a
method’s throws clause.
Error
• An Error is a subclass of Throwable that indicates serious
problems that a reasonable application should not try to
catch.
• Most such errors are abnormal conditions that should
never occur.
• A method is not required to declare in its throws clause any
subclasses of Error that might be thrown during the
execution of the method but not caught.
• Error and its subclasses are regarded as unchecked
exceptions for the purposes of compile-time checking of
exceptions.
• Examples: OutOfMemoryError, VirtualMachineError,
AssertionError, IOError.
User Defined Exceptions
• These are business or application exceptions.
• Class Name ends with the string Exception.
Examples: InsufficientFundsException,
AccountClosedException.
• If user defined exception is a checked
exception, it should extend Exception,
otherwise it should extend RuntimeException.
• Add custom fields and getters/setters to store
more information.
Nesting Exceptions
• An exception can nest or contain another
exception.
• Many APIs throw a generic exception which
contain the implementation exception.
• Example: Spring Framework
DataAccessException nests the JDBC
SQLException.
• SomeApiException.getCause() retrieves the
implementation exception.
Recommendations – part 1
• Use exceptions only for exceptional conditions.
• Close or release resources in the finally block.
• Use checked exceptions for recoverable errors.
• Runtime exceptions indicate programming errors - do not catch
them.
• Errors are unchecked exceptions – generally should not be caught.
• Catch exceptions only where you can handle them meaningfully,
otherwise re-throw them.
• Use standard exceptions as far as possible.
• Document all checked exceptions thrown by each method using the
@throws tag or @exception tag in the method’s java doc.
Recommendation – part 2
• Include appropriate details from the surrounding
context when creating & throwing exceptions.
• Log or print the root exception before you throw a new
wrapped exception.
• Avoid empty catch blocks – swallowing exceptions –
hides errors and exceptions – leaves object or
application in a corrupt or unusable state.
• Exceptions are costly in terms of performance =>
minimize use of checked exceptions, try to convert
checked exceptions into unchecked exceptions.

More Related Content

PPTX
Java Exceptions and Exception Handling
ODP
Exception Handling In Java 15734
PPTX
Exception handling in java
PPTX
Exception handling in JAVA
PPTX
Exception handling in Java
PPTX
Java Exceptions Best Practices
PPTX
Exception handling in java
PPTX
Exception handling in java
Java Exceptions and Exception Handling
Exception Handling In Java 15734
Exception handling in java
Exception handling in JAVA
Exception handling in Java
Java Exceptions Best Practices
Exception handling in java
Exception handling in java

What's hot (20)

PPTX
Java Exception Handling and Applets
PPT
Exception Handling Java
PPTX
Java exception handling
PPTX
Exception Handling in Java
PDF
javaexceptions
PPT
Exception handling
PPT
exception handling in java
ODP
Exception Handling In Java
PPTX
Exception handling in java
PPT
Java: Exception
PPT
12 exception handling
PPT
Exception handling
PPTX
Presentation on-exception-handling
DOCX
Java Exception handling
PDF
Exception handling
PPT
Exception handling in java
PPTX
Exception handling in java
PPTX
Exception handling in java
PPTX
Exception handling
Java Exception Handling and Applets
Exception Handling Java
Java exception handling
Exception Handling in Java
javaexceptions
Exception handling
exception handling in java
Exception Handling In Java
Exception handling in java
Java: Exception
12 exception handling
Exception handling
Presentation on-exception-handling
Java Exception handling
Exception handling
Exception handling in java
Exception handling in java
Exception handling in java
Exception handling
Ad

Similar to Introduction to java exceptions (20)

PPTX
using Java Exception Handling in Java.pptx
PPT
A36519192_21789_4_2018_Exception Handling.ppt
PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
Exceptions in Java
PPTX
UNIT III 2021R.pptx
PPTX
UNIT III 2021R.pptx
PPTX
Java-Unit 3- Chap2 exception handling
PPTX
Chap2 exception handling
PPT
Exception handling
PPTX
UNIT-3.pptx Exception Handling and Multithreading
PDF
Chapter 5 Exception Handling (1).pdf
PPTX
Exception handling in java-PPT.pptx
PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
PPTX
Week 4 - 5 Debugging Code and Analyzing Logic Errors.pptx
PDF
Exception handling
PDF
Exception handling
PPTX
Training material exceptions v1
PPTX
PPT
exception-handling-in-java.ppt unit 2
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
using Java Exception Handling in Java.pptx
A36519192_21789_4_2018_Exception Handling.ppt
Ch-1_5.pdf this is java tutorials for all
Exceptions in Java
UNIT III 2021R.pptx
UNIT III 2021R.pptx
Java-Unit 3- Chap2 exception handling
Chap2 exception handling
Exception handling
UNIT-3.pptx Exception Handling and Multithreading
Chapter 5 Exception Handling (1).pdf
Exception handling in java-PPT.pptx
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
Week 4 - 5 Debugging Code and Analyzing Logic Errors.pptx
Exception handling
Exception handling
Training material exceptions v1
exception-handling-in-java.ppt unit 2
unit 4 msbte syallbus for sem 4 2024-2025
Ad

More from Sujit Kumar (20)

PPTX
Introduction to OOP with java
PPTX
SFDC Database Basics
PPTX
SFDC Database Security
PPTX
SFDC Social Applications
PPTX
SFDC Other Platform Features
PPTX
SFDC Outbound Integrations
PPTX
SFDC Inbound Integrations
PPTX
SFDC UI - Advanced Visualforce
PPTX
SFDC UI - Introduction to Visualforce
PPTX
SFDC Deployments
PPTX
SFDC Batch Apex
PPTX
SFDC Data Loader
PPTX
SFDC Advanced Apex
PPTX
SFDC Introduction to Apex
PPTX
SFDC Database Additional Features
PPTX
Introduction to SalesForce
PPTX
More about java strings - Immutability and String Pool
PPTX
Hibernate First and Second level caches
PPTX
Java equals hashCode Contract
PPTX
Java Comparable and Comparator
Introduction to OOP with java
SFDC Database Basics
SFDC Database Security
SFDC Social Applications
SFDC Other Platform Features
SFDC Outbound Integrations
SFDC Inbound Integrations
SFDC UI - Advanced Visualforce
SFDC UI - Introduction to Visualforce
SFDC Deployments
SFDC Batch Apex
SFDC Data Loader
SFDC Advanced Apex
SFDC Introduction to Apex
SFDC Database Additional Features
Introduction to SalesForce
More about java strings - Immutability and String Pool
Hibernate First and Second level caches
Java equals hashCode Contract
Java Comparable and Comparator

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
KodekX | Application Modernization Development
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPT
Teaching material agriculture food technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Spectroscopy.pptx food analysis technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Review of recent advances in non-invasive hemoglobin estimation
Understanding_Digital_Forensics_Presentation.pptx
KodekX | Application Modernization Development
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Network Security Unit 5.pdf for BCA BBA.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation_ Review paper, used for researhc scholars
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Teaching material agriculture food technology
Reach Out and Touch Someone: Haptics and Empathic Computing
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
“AI and Expert System Decision Support & Business Intelligence Systems”
Spectroscopy.pptx food analysis technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Weekly Chronicles - August'25 Week I
Building Integrated photovoltaic BIPV_UPV.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Review of recent advances in non-invasive hemoglobin estimation

Introduction to java exceptions

  • 1. Introduction To Java Exceptions Sujit Kumar Zenolocity LLC © 2013-2023
  • 2. Exceptions • Events that disrupt the normal flow of execution. • Exception Object 1) cause (can contain another exception), 2) detailed message. • Can be thrown by the programmer using the throw keyword. • Can be caught by the programmer using the catch keyword.
  • 3. Benefits of Java Exception Handling • Cleaner code by separating error handling code from normal or happy path code. • Propagate errors up the call stack where they can be handled meaningfully. • Helps to categorize exceptions using the exception hierarchy.
  • 4. Types of Errors • JVM Errors => OutOfMemoryError, StackOverflowError, LinkageError • System Errors => FileNotFoundException, IOException, NullPointerException, ArrayIndexOutOfBoundsException • Application Errors => InsufficientFundsException (transfer balance from one account to another). • JVM & System Errors are built-in, Application Errors are user defined.
  • 6. Exception Handling – try, catch, finally • Try block – normal flow of execution. • Catch blocks ( 1 or more) – exception handling code, are like if-else-if statements – only 1 can potentially execute. • Derived class exception should be caught before a base class exception in the catch blocks. • If an exception is thrown that is not handled, it is propagated up the call stack.
  • 7. Finally Block • Finally block – clean up code, always gets executed, even when you have a return in try/catch or any exception is re-thrown. • When does finally not execute ? – It may not execute when JVM terminates (via System.exit()) or current thread is killed or system runs out of memory. • If an exception is thrown that is not handled, it is propagated up the call stack.
  • 8. Checked & Unchecked Exceptions • Checked – compiler forces you to either catch them or declare in the throws clause. Use it for recoverable errors. • Unchecked – RuntimeException and its subclasses are unchecked exceptions. Compiler does not force you to catch them. Unchecked exceptions do not need to be declared in a method’s throws clause.
  • 9. Error • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. • Most such errors are abnormal conditions that should never occur. • A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught. • Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions. • Examples: OutOfMemoryError, VirtualMachineError, AssertionError, IOError.
  • 10. User Defined Exceptions • These are business or application exceptions. • Class Name ends with the string Exception. Examples: InsufficientFundsException, AccountClosedException. • If user defined exception is a checked exception, it should extend Exception, otherwise it should extend RuntimeException. • Add custom fields and getters/setters to store more information.
  • 11. Nesting Exceptions • An exception can nest or contain another exception. • Many APIs throw a generic exception which contain the implementation exception. • Example: Spring Framework DataAccessException nests the JDBC SQLException. • SomeApiException.getCause() retrieves the implementation exception.
  • 12. Recommendations – part 1 • Use exceptions only for exceptional conditions. • Close or release resources in the finally block. • Use checked exceptions for recoverable errors. • Runtime exceptions indicate programming errors - do not catch them. • Errors are unchecked exceptions – generally should not be caught. • Catch exceptions only where you can handle them meaningfully, otherwise re-throw them. • Use standard exceptions as far as possible. • Document all checked exceptions thrown by each method using the @throws tag or @exception tag in the method’s java doc.
  • 13. Recommendation – part 2 • Include appropriate details from the surrounding context when creating & throwing exceptions. • Log or print the root exception before you throw a new wrapped exception. • Avoid empty catch blocks – swallowing exceptions – hides errors and exceptions – leaves object or application in a corrupt or unusable state. • Exceptions are costly in terms of performance => minimize use of checked exceptions, try to convert checked exceptions into unchecked exceptions.

Editor's Notes

  • #6: Exception hierarchy can also exist for user defined application exceptions.