SlideShare a Scribd company logo
1 of 39
Download to read offline
Handling Errors During the Program Execution
Exception Handling
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
Table of Contents
1. What Are Exceptions?
 The Exception Class
 Types of Exceptions and Their Hierarchy
2. Handling Exceptions
3. Raising (Throwing) Exceptions
4. Best Practices
5. Creating Custom Exceptions
2
sli.do
#java-advanced
Have a Question?
What are Exceptions?
The Paradigm of Exceptions in OOP
 Simplify code construction and maintenance
 Allow the problematic situations to be processed
at multiple levels
 Exception objects have detailed information about
the error
What Are Exceptions?
5
There are two ways to write error-free programs; only the third
one works. (Alan J. Perlis)
 Exceptions in Java are objects
 The Throwable class is a base for
all exceptions in JVM
 Contains information for the cause of the error
 Message – a text description of the exception
 StackTrace – the snapshot of the stack at the
moment of exception throwing
The Throwable Class
6
 Java exceptions inherit from Throwable
 Below Throwable are:
 Error - not expected to be caught under normal
circumstances from the program
 Example - StackOverflowError
 Exception
 Used for exceptional conditions that user programs should catch
 User-defined exceptions
Types of Exceptions
7
 Exceptions are two types:
 Checked - an exception that is checked (notified) by the
compiler at compilation-time
 Also called as Compile Time exceptions
 Unchecked - an exception that occurs at the time of execution
 Also called as Runtime Exceptions
Exceptions
8
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
} FileNotFoundException
Exception Hierarchy
9
Handling Exceptions
Catching and Processing Errors
Handling Exceptions
 In Java exceptions can be handled by the
try-catch construction
 catch blocks can be used multiple times to process
different exception types
11
try {
// Do some work that can raise an exception
} catch (SomeException) {
// Handle the caught exception
}
Multiple Catch Blocks – Example
12
String s = sc.nextLine();
try {
Integer.parseInt(s);
System.out.printf(
"You entered a valid integer number %s.", s);
} catch (NumberFormatException ex) {
System.out.println("Invalid integer number!");
}
 When catching an exception of a particular class, all its
inheritors (child exceptions) are caught too, e.g.
 Handles IndexOutOfBoundsException and its descendants
ArrayIndexOutOfBoundsException and
StringIndexOutOfBoundsException
Handling Exceptions
13
try {
// Do some work that can cause an exception
} catch (IndexOutOfBoundsException ae) {
// Handle the caught arithmetic exception
}
Find the Mistake!
14
String str = sc.nextLine();
try {
Integer.parseInt(str);
} catch (Exception ex) {
System.out.println("Cannot parse the number!");
} catch (NumberFormatException ex) {
System.out.println("Invalid integer number!");
}
Should be last
Unreachable code
 Unmanaged code can throw other exceptions
 For handling all exceptions (even unmanaged) use the
construction:
Handling All Exceptions
15
try {
// Do some work that can raise any exception
} catch (Exception ex) {
// Handle the caught exception
}
 The statement:
 Ensures execution of a given block in all cases
 When exception is raised or not in the try block
 Used for execution of cleaning-up code, e.g. releasing resources
The try-finally Statement
16
try {
// Do some work that can cause an exception
} finally {
// This block will always execute
}
try-finally – Example
17
static void testTryFinally() {
System.out.println("Code executed before try-finally.");
try {
String str = sc.nextLine();
Integer.parseInt(str);
System.out.println("Parsing was successful.");
return; // Exit from the current method
} catch (NumberFormatException ex) {
System.out.println("Parsing failed!");
} finally {
System.out.println("This cleanup code is always executed.");
}
System.out.println("This code is after the try-finally block.");
}
How Do Exceptions Work?
18
try Run this code
catch
Execute this code when there
is an exception
finally Always run this code
Handling Exceptions
Live Demo
Throwing Exceptions
 Exceptions are thrown (raised) by the throw keyword
 Used to notify the calling code in case of an error
or unusual situation
 When an exception is thrown:
 The program execution stops
 The exception travels over the stack
 Until a matching catch block is reached to handle it
 Unhandled exceptions display an error message
Throwing Exceptions
21
 Throwing an exception with an error message:
 Exceptions can accept message and cause:
 Note: if the original exception is not passed, the initial cause of
the exception is lost
Using throw Keyword
22
throw new IllegalArgumentException("Invalid amount!");
try {
…
} catch (SQLException sqlEx) {
throw new IllegalStateException("Cannot save invoice.", sqlEx);
}
 Caught exceptions can be re-thrown again:
Re-Throwing Exceptions
23
try {
Integer.parseInt(str);
} catch (NumberFormatException ex) {
System.out.println("Parse failed!");
throw ex; // Re-throw the caught exception
}
Throwing Exceptions – Example
24
public static double sqrt(double value) {
if (value < 0)
throw new IllegalArgumentException(
"Sqrt for negative numbers is undefined!");
return Math.sqrt(value);
}
public static void main(String[] args) {
try {
sqrt(-1);
} catch (IllegalArgumentException ex) {
System.err.println("Error: " + ex.getMessage());
ex.printStackTrace();
}
}
Throwing Exceptions
Live Demo
Best Practices
 Catch blocks should:
 Begin with the exceptions lowest in the hierarchy
 Continue with the more general exceptions
 Otherwise a compilation error will occur
 Each catch block should handle only these exceptions
which it expects
 If a method is not competent to handle an exception, it should
leave it unhandled
 Handling all exceptions disregarding their type is a popular
bad practice (anti-pattern)!
Using catch Block
27
 When an application attempts to use null in a case where
an object is required – NullPointerException
 An array has been accessed with an illegal index –
ArrayIndexOutOfBoundsException
 An index is either negative or greater than the size of
the string – StringIndexOutOfBoundsException
 Attempts to convert a inappropriate string to one of the
numeric types - NumberFormatException
Choosing the Exception Type (1)
28
 When an exceptional arithmetic condition has occurred –
ArithmeticException
 Attempts to cast an object to a subclass of which it is not an
instance – ClassCastException
 A method has been passed an illegal or inappropriate
argument - IllegalArgumentException
Choosing the Exception Type (2)
29
 When raising an exception, always pass to the constructor a
good explanation message
 When throwing an exception always pass a good description
of the problem
 The exception message should explain what causes the problem
and how to solve it
 Good: "Size should be integer in range [1…15]"
 Good: "Invalid state. First call Initialize()"
 Bad: "Unexpected error"
 Bad: "Invalid argument"
Exceptions – Best Practices (1)
30
 Exceptions can decrease the application performance
 Throw exceptions only in situations which are really exceptional
and should be handled
 Do not throw exceptions in the normal program control flow
 JVM could throw exceptions at any time with no way to
predict them
 E.g. StackOverflowError
Exceptions – Best Practices (2)
31
Custom Exceptions
32
 Custom exceptions inherit an exception class
(commonly – Exception)
 Thrown just like any other exception
Creating Custom Exceptions
33
public class TankException extends Exception {
public TankException(String msg) {
super(msg);
}
}
throw new TankException("Not enough fuel to travel");
 …
 …
 …
Summary
34
 Exceptions provide a flexible error
handling mechanism
 Unhandled exceptions cause error
messages
 try-finally ensures a given code
block is always executed
 Even when an exception is thrown
 https://softuni.bg/modules/59/java-advanced
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
39

More Related Content

Similar to Exception Handling.pdf

Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
exception handling in java
exception handling in javaexception handling in java
exception handling in javaAbinaya B
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1sotlsoc
 

Similar to Exception Handling.pdf (20)

UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Satish training ppt
Satish training pptSatish training ppt
Satish training ppt
 
Exception handling
Exception handlingException handling
Exception handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java unit3
Java unit3Java unit3
Java unit3
 
Exception handling
Exception handlingException handling
Exception handling
 
exception handling in java
exception handling in javaexception handling in java
exception handling in java
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1
 

Recently uploaded

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 

Recently uploaded (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 

Exception Handling.pdf

  • 1. Handling Errors During the Program Execution Exception Handling Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2. Table of Contents 1. What Are Exceptions?  The Exception Class  Types of Exceptions and Their Hierarchy 2. Handling Exceptions 3. Raising (Throwing) Exceptions 4. Best Practices 5. Creating Custom Exceptions 2
  • 4. What are Exceptions? The Paradigm of Exceptions in OOP
  • 5.  Simplify code construction and maintenance  Allow the problematic situations to be processed at multiple levels  Exception objects have detailed information about the error What Are Exceptions? 5 There are two ways to write error-free programs; only the third one works. (Alan J. Perlis)
  • 6.  Exceptions in Java are objects  The Throwable class is a base for all exceptions in JVM  Contains information for the cause of the error  Message – a text description of the exception  StackTrace – the snapshot of the stack at the moment of exception throwing The Throwable Class 6
  • 7.  Java exceptions inherit from Throwable  Below Throwable are:  Error - not expected to be caught under normal circumstances from the program  Example - StackOverflowError  Exception  Used for exceptional conditions that user programs should catch  User-defined exceptions Types of Exceptions 7
  • 8.  Exceptions are two types:  Checked - an exception that is checked (notified) by the compiler at compilation-time  Also called as Compile Time exceptions  Unchecked - an exception that occurs at the time of execution  Also called as Runtime Exceptions Exceptions 8 public static void main(String args[]) { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } FileNotFoundException
  • 10. Handling Exceptions Catching and Processing Errors
  • 11. Handling Exceptions  In Java exceptions can be handled by the try-catch construction  catch blocks can be used multiple times to process different exception types 11 try { // Do some work that can raise an exception } catch (SomeException) { // Handle the caught exception }
  • 12. Multiple Catch Blocks – Example 12 String s = sc.nextLine(); try { Integer.parseInt(s); System.out.printf( "You entered a valid integer number %s.", s); } catch (NumberFormatException ex) { System.out.println("Invalid integer number!"); }
  • 13.  When catching an exception of a particular class, all its inheritors (child exceptions) are caught too, e.g.  Handles IndexOutOfBoundsException and its descendants ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException Handling Exceptions 13 try { // Do some work that can cause an exception } catch (IndexOutOfBoundsException ae) { // Handle the caught arithmetic exception }
  • 14. Find the Mistake! 14 String str = sc.nextLine(); try { Integer.parseInt(str); } catch (Exception ex) { System.out.println("Cannot parse the number!"); } catch (NumberFormatException ex) { System.out.println("Invalid integer number!"); } Should be last Unreachable code
  • 15.  Unmanaged code can throw other exceptions  For handling all exceptions (even unmanaged) use the construction: Handling All Exceptions 15 try { // Do some work that can raise any exception } catch (Exception ex) { // Handle the caught exception }
  • 16.  The statement:  Ensures execution of a given block in all cases  When exception is raised or not in the try block  Used for execution of cleaning-up code, e.g. releasing resources The try-finally Statement 16 try { // Do some work that can cause an exception } finally { // This block will always execute }
  • 17. try-finally – Example 17 static void testTryFinally() { System.out.println("Code executed before try-finally."); try { String str = sc.nextLine(); Integer.parseInt(str); System.out.println("Parsing was successful."); return; // Exit from the current method } catch (NumberFormatException ex) { System.out.println("Parsing failed!"); } finally { System.out.println("This cleanup code is always executed."); } System.out.println("This code is after the try-finally block."); }
  • 18. How Do Exceptions Work? 18 try Run this code catch Execute this code when there is an exception finally Always run this code
  • 21.  Exceptions are thrown (raised) by the throw keyword  Used to notify the calling code in case of an error or unusual situation  When an exception is thrown:  The program execution stops  The exception travels over the stack  Until a matching catch block is reached to handle it  Unhandled exceptions display an error message Throwing Exceptions 21
  • 22.  Throwing an exception with an error message:  Exceptions can accept message and cause:  Note: if the original exception is not passed, the initial cause of the exception is lost Using throw Keyword 22 throw new IllegalArgumentException("Invalid amount!"); try { … } catch (SQLException sqlEx) { throw new IllegalStateException("Cannot save invoice.", sqlEx); }
  • 23.  Caught exceptions can be re-thrown again: Re-Throwing Exceptions 23 try { Integer.parseInt(str); } catch (NumberFormatException ex) { System.out.println("Parse failed!"); throw ex; // Re-throw the caught exception }
  • 24. Throwing Exceptions – Example 24 public static double sqrt(double value) { if (value < 0) throw new IllegalArgumentException( "Sqrt for negative numbers is undefined!"); return Math.sqrt(value); } public static void main(String[] args) { try { sqrt(-1); } catch (IllegalArgumentException ex) { System.err.println("Error: " + ex.getMessage()); ex.printStackTrace(); } }
  • 27.  Catch blocks should:  Begin with the exceptions lowest in the hierarchy  Continue with the more general exceptions  Otherwise a compilation error will occur  Each catch block should handle only these exceptions which it expects  If a method is not competent to handle an exception, it should leave it unhandled  Handling all exceptions disregarding their type is a popular bad practice (anti-pattern)! Using catch Block 27
  • 28.  When an application attempts to use null in a case where an object is required – NullPointerException  An array has been accessed with an illegal index – ArrayIndexOutOfBoundsException  An index is either negative or greater than the size of the string – StringIndexOutOfBoundsException  Attempts to convert a inappropriate string to one of the numeric types - NumberFormatException Choosing the Exception Type (1) 28
  • 29.  When an exceptional arithmetic condition has occurred – ArithmeticException  Attempts to cast an object to a subclass of which it is not an instance – ClassCastException  A method has been passed an illegal or inappropriate argument - IllegalArgumentException Choosing the Exception Type (2) 29
  • 30.  When raising an exception, always pass to the constructor a good explanation message  When throwing an exception always pass a good description of the problem  The exception message should explain what causes the problem and how to solve it  Good: "Size should be integer in range [1…15]"  Good: "Invalid state. First call Initialize()"  Bad: "Unexpected error"  Bad: "Invalid argument" Exceptions – Best Practices (1) 30
  • 31.  Exceptions can decrease the application performance  Throw exceptions only in situations which are really exceptional and should be handled  Do not throw exceptions in the normal program control flow  JVM could throw exceptions at any time with no way to predict them  E.g. StackOverflowError Exceptions – Best Practices (2) 31
  • 33.  Custom exceptions inherit an exception class (commonly – Exception)  Thrown just like any other exception Creating Custom Exceptions 33 public class TankException extends Exception { public TankException(String msg) { super(msg); } } throw new TankException("Not enough fuel to travel");
  • 34.  …  …  … Summary 34  Exceptions provide a flexible error handling mechanism  Unhandled exceptions cause error messages  try-finally ensures a given code block is always executed  Even when an exception is thrown
  • 38.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 39.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 39