SlideShare a Scribd company logo
1 of 39
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

What's hot

What's hot (20)

Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
conditional statements
conditional statementsconditional statements
conditional statements
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Java Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting StartedJava Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting Started
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java programs
Java programsJava programs
Java programs
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Java generics final
Java generics finalJava generics final
Java generics final
 

Similar to 12. Java Exceptions and error handling

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

Similar to 12. Java Exceptions and error handling (20)

Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdf
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handlin g C#.pptx
Exception Handlin g C#.pptxException Handlin g C#.pptx
Exception Handlin g C#.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Satish training ppt
Satish training pptSatish training ppt
Satish training ppt
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
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
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

More from Intro C# Book

More from Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 

Recently uploaded

一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
ayvbos
 
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理
F
 
一比一原版澳大利亚迪肯大学毕业证如何办理
一比一原版澳大利亚迪肯大学毕业证如何办理一比一原版澳大利亚迪肯大学毕业证如何办理
一比一原版澳大利亚迪肯大学毕业证如何办理
SS
 
一比一原版贝德福特大学毕业证学位证书
一比一原版贝德福特大学毕业证学位证书一比一原版贝德福特大学毕业证学位证书
一比一原版贝德福特大学毕业证学位证书
F
 
原版定制英国赫瑞瓦特大学毕业证原件一模一样
原版定制英国赫瑞瓦特大学毕业证原件一模一样原版定制英国赫瑞瓦特大学毕业证原件一模一样
原版定制英国赫瑞瓦特大学毕业证原件一模一样
AS
 
Abortion Clinic in Germiston +27791653574 WhatsApp Abortion Clinic Services i...
Abortion Clinic in Germiston +27791653574 WhatsApp Abortion Clinic Services i...Abortion Clinic in Germiston +27791653574 WhatsApp Abortion Clinic Services i...
Abortion Clinic in Germiston +27791653574 WhatsApp Abortion Clinic Services i...
mikehavy0
 
一比一原版桑佛德大学毕业证成绩单申请学校Offer快速办理
一比一原版桑佛德大学毕业证成绩单申请学校Offer快速办理一比一原版桑佛德大学毕业证成绩单申请学校Offer快速办理
一比一原版桑佛德大学毕业证成绩单申请学校Offer快速办理
apekaom
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
F
 
一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理
F
 
一比一原版(Polytechnic毕业证书)新加坡理工学院毕业证原件一模一样
一比一原版(Polytechnic毕业证书)新加坡理工学院毕业证原件一模一样一比一原版(Polytechnic毕业证书)新加坡理工学院毕业证原件一模一样
一比一原版(Polytechnic毕业证书)新加坡理工学院毕业证原件一模一样
AS
 

Recently uploaded (20)

A LOOK INTO NETWORK TECHNOLOGIES MAINLY WAN.pptx
A LOOK INTO NETWORK TECHNOLOGIES MAINLY WAN.pptxA LOOK INTO NETWORK TECHNOLOGIES MAINLY WAN.pptx
A LOOK INTO NETWORK TECHNOLOGIES MAINLY WAN.pptx
 
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
 
Lowongan Kerja LC Yogyakarta Terbaru 085746015303
Lowongan Kerja LC Yogyakarta Terbaru 085746015303Lowongan Kerja LC Yogyakarta Terbaru 085746015303
Lowongan Kerja LC Yogyakarta Terbaru 085746015303
 
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理
 
一比一原版澳大利亚迪肯大学毕业证如何办理
一比一原版澳大利亚迪肯大学毕业证如何办理一比一原版澳大利亚迪肯大学毕业证如何办理
一比一原版澳大利亚迪肯大学毕业证如何办理
 
一比一原版贝德福特大学毕业证学位证书
一比一原版贝德福特大学毕业证学位证书一比一原版贝德福特大学毕业证学位证书
一比一原版贝德福特大学毕业证学位证书
 
原版定制英国赫瑞瓦特大学毕业证原件一模一样
原版定制英国赫瑞瓦特大学毕业证原件一模一样原版定制英国赫瑞瓦特大学毕业证原件一模一样
原版定制英国赫瑞瓦特大学毕业证原件一模一样
 
Down bad crying at the gym t shirtsDown bad crying at the gym t shirts
Down bad crying at the gym t shirtsDown bad crying at the gym t shirtsDown bad crying at the gym t shirtsDown bad crying at the gym t shirts
Down bad crying at the gym t shirtsDown bad crying at the gym t shirts
 
Washington Football Commanders Redskins Feathers Shirt
Washington Football Commanders Redskins Feathers ShirtWashington Football Commanders Redskins Feathers Shirt
Washington Football Commanders Redskins Feathers Shirt
 
Abortion Clinic in Germiston +27791653574 WhatsApp Abortion Clinic Services i...
Abortion Clinic in Germiston +27791653574 WhatsApp Abortion Clinic Services i...Abortion Clinic in Germiston +27791653574 WhatsApp Abortion Clinic Services i...
Abortion Clinic in Germiston +27791653574 WhatsApp Abortion Clinic Services i...
 
一比一原版桑佛德大学毕业证成绩单申请学校Offer快速办理
一比一原版桑佛德大学毕业证成绩单申请学校Offer快速办理一比一原版桑佛德大学毕业证成绩单申请学校Offer快速办理
一比一原版桑佛德大学毕业证成绩单申请学校Offer快速办理
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
 
一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
APNIC Updates presented by Paul Wilson at CaribNOG 27
APNIC Updates presented by Paul Wilson at  CaribNOG 27APNIC Updates presented by Paul Wilson at  CaribNOG 27
APNIC Updates presented by Paul Wilson at CaribNOG 27
 
Research Assignment - NIST SP800 [172 A] - Presentation.pptx
Research Assignment - NIST SP800 [172 A] - Presentation.pptxResearch Assignment - NIST SP800 [172 A] - Presentation.pptx
Research Assignment - NIST SP800 [172 A] - Presentation.pptx
 
Loker Pemandu Lagu LC Semarang 085746015303
Loker Pemandu Lagu LC Semarang 085746015303Loker Pemandu Lagu LC Semarang 085746015303
Loker Pemandu Lagu LC Semarang 085746015303
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
一比一原版(Polytechnic毕业证书)新加坡理工学院毕业证原件一模一样
一比一原版(Polytechnic毕业证书)新加坡理工学院毕业证原件一模一样一比一原版(Polytechnic毕业证书)新加坡理工学院毕业证原件一模一样
一比一原版(Polytechnic毕业证书)新加坡理工学院毕业证原件一模一样
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
 

12. Java Exceptions and error handling

  • 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

Editor's Notes

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  6. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  7. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  8. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  9. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  10. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  11. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  12. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*