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

Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
conditional statements
conditional statementsconditional statements
conditional statementsJames Brotsos
 
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.Nishan Barot
 
Java Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting StartedJava Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting StartedSvetlin Nakov
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 

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

Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdflsdfjldskjf
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Exception Handlin g C#.pptx
Exception Handlin g C#.pptxException Handlin g C#.pptx
Exception Handlin g C#.pptxR S Anu Prabha
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
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
Exception HandlingException Handling
Exception HandlingSunil OS
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 

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
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java 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

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 traversalIntro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
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 complexityIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories Intro C# Book
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro 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

GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebJames Anderson
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneRussian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneCall girls in Ahmedabad High profile
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Roomgirls4nights
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Servicesexy call girls service in goa
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsstephieert
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024APNIC
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$kojalkojal131
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of indiaimessage0108
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Delhi Call girls
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...APNIC
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 

Recently uploaded (20)

GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneRussian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girls
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of india
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 

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.*