KEMBAR78
12. Java Exceptions and error handling | PPTX
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

12. Java Exceptions and error handling

  • 1.
    Handling Errors Duringthe 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
  • 3.
  • 4.
    What are Exceptions? TheParadigm of Exceptions in OOP
  • 5.
     Simplify codeconstruction 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 inJava 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 exceptionsinherit 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 aretwo 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
  • 9.
  • 10.
  • 11.
    Handling Exceptions  InJava 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 catchingan 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 Stringstr = 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 codecan 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 staticvoid 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 ExceptionsWork? 18 try Run this code catch Execute this code when there is an exception finally Always run this code
  • 19.
  • 20.
  • 21.
     Exceptions arethrown (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 anexception 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 exceptionscan 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(); } }
  • 25.
  • 26.
  • 27.
     Catch blocksshould:  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 anapplication 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 anexceptional 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 raisingan 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 candecrease 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
  • 32.
  • 33.
     Custom exceptionsinherit 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
  • 35.
  • 36.
  • 37.
  • 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

  • #8 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #14 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #15 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #16 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #17 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #18 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #22 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #23 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #24 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #25 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #28 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #32 (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*