SlideShare uma empresa Scribd logo
1 de 13
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.
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.

Mais conteúdo relacionado

Mais procurados

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
aptechsravan
 

Mais procurados (20)

Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Exception handling
Exception handling Exception 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 in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException 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
 

Semelhante a Introduction to java exceptions

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
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 

Semelhante a Introduction to java exceptions (20)

A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
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
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
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
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
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
Exception handlingException handling
Exception handling
 
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
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
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
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Exception handling
Exception handlingException handling
Exception handling
 

Mais de Sujit Kumar

Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
Sujit Kumar
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and Comparator
Sujit Kumar
 

Mais de Sujit Kumar (20)

Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
 
SFDC Database Basics
SFDC Database BasicsSFDC Database Basics
SFDC Database Basics
 
SFDC Database Security
SFDC Database SecuritySFDC Database Security
SFDC Database Security
 
SFDC Social Applications
SFDC Social ApplicationsSFDC Social Applications
SFDC Social Applications
 
SFDC Other Platform Features
SFDC Other Platform FeaturesSFDC Other Platform Features
SFDC Other Platform Features
 
SFDC Outbound Integrations
SFDC Outbound IntegrationsSFDC Outbound Integrations
SFDC Outbound Integrations
 
SFDC Inbound Integrations
SFDC Inbound IntegrationsSFDC Inbound Integrations
SFDC Inbound Integrations
 
SFDC UI - Advanced Visualforce
SFDC UI - Advanced VisualforceSFDC UI - Advanced Visualforce
SFDC UI - Advanced Visualforce
 
SFDC UI - Introduction to Visualforce
SFDC UI -  Introduction to VisualforceSFDC UI -  Introduction to Visualforce
SFDC UI - Introduction to Visualforce
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC Deployments
 
SFDC Batch Apex
SFDC Batch ApexSFDC Batch Apex
SFDC Batch Apex
 
SFDC Data Loader
SFDC Data LoaderSFDC Data Loader
SFDC Data Loader
 
SFDC Advanced Apex
SFDC Advanced Apex SFDC Advanced Apex
SFDC Advanced Apex
 
SFDC Introduction to Apex
SFDC Introduction to ApexSFDC Introduction to Apex
SFDC Introduction to Apex
 
SFDC Database Additional Features
SFDC Database Additional FeaturesSFDC Database Additional Features
SFDC Database Additional Features
 
Introduction to SalesForce
Introduction to SalesForceIntroduction to SalesForce
Introduction to SalesForce
 
More about java strings - Immutability and String Pool
More about java strings - Immutability and String PoolMore about java strings - Immutability and String Pool
More about java strings - Immutability and String Pool
 
Hibernate First and Second level caches
Hibernate First and Second level cachesHibernate First and Second level caches
Hibernate First and Second level caches
 
Java equals hashCode Contract
Java equals hashCode ContractJava equals hashCode Contract
Java equals hashCode Contract
 
Java Comparable and Comparator
Java Comparable and ComparatorJava Comparable and Comparator
Java Comparable and Comparator
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

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.
  • 5.
  • 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.

Notas do Editor

  1. Exception hierarchy can also exist for user defined application exceptions.