06 Exceptions
06 Exceptions
2
Syntax Errors
• Syntax errors are mistakes in the grammar of a
language
3
Run-time Errors or Exceptions
• Run-time errors
– Occur during program execution (following a successful compilation)
– Occur when the JVM detects an operation that it knows to be incorrect
– Cause the JVM to throw an exception
• Examples of run-time errors include
4
The Big Picture
5
Error vs Exception
• Error:
• Errors are thrown at run time when a serious problem
occurs and cannot be recovered.
• Indicate abnormal situations that should never happen.
• Primarily arise due to the lack of system resources.
• Errors are regarded as unchecked exceptions.
• Applications should not try to catch and handle them.
• Exception:
• Abnormal conditions that applications might want to catch
and handle.
• Can be recovered using a try-catch block.
• Can be checked or unchecked.
• Techniques used for exception handling are try-catch
block, throws keyword, and try-with-resources block. 6
Checked vs Unchecked Exception
• Checked exceptions:
• Exceptions that are checked at compile time.
• If some code within a method can cause a checked
exception, then the method must either handle the
exception or it must declare the exception to the caller
using the throws keyword within its signature
• Fully checked exception is a checked exception where all
its child classes are also checked.
• Partially checked exception is a checked exception where
some of its child classes are unchecked.
• Unchecked exceptions :
• Exceptions that are not checked at compile time.
• Not required to be handled by the program.
• All children of Error and RuntimeException classes are
unchecked exceptions.
• Everything else under Throwable is checked. 7
Exception-Handling
• Exception:
• an indication of a problem that occurs during a program’s
execution
• Exception handling:
• Allows resolving exceptions that may occur so program can
continue or terminate gracefully
• Enables programmers to create programs that are more robust
and fault-tolerant
• Improves clarity and modifiability
8
Example (1)
1 // Fig. 13.1: DivideByZeroNoExceptionHandling.java
2 // An application that attempts to divide by zero.
3 import java.util.Scanner;
4 Attempt to divide;
public class DivideByZeroNoExceptionHandling
5
denominator may be zero
6 {
7 // demonstrates throwing an exception when a divide-by-zero occurs
8 public static int quotient( int numerator, int denominator )
9 {
10 return numerator / denominator; // possible division by zero
11 } // end method quotient
12
13 public static void main( String args[] )
14 {
15 Scanner scanner = new Scanner( System.in ); // scanner for input
16
17 System.out.print( "Please enter an integer numerator: " );
18 int numerator = scanner.nextInt();
19 System.out.print( "Please enter an integer denominator: " ); Read input; exception occurs if
20 int denominator = scanner.nextInt(); input is not a valid integer
21
22 int result = quotient( numerator, denominator );
23 System.out.printf(
24 "\nResult: %d / %d = %d\n", numerator, denominator, result );
25 } // end main
26 } // end class DivideByZeroNoExceptionHandling
9
Example (1)
InputMismatchException
Please enter an integer numerator: 100
Please enter an integer denominator: hello
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at
DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:20)
10
Enclosing Code in a try Block
• try block
• encloses code that might throw an exception and the code
that should not execute if an exception occurs
• Consists of keyword try followed by a block of code enclosed
in curly braces
• try statement – consists of try block and corresponding
catch and/or finally blocks
11
Catching Block
• catch block - catches (i.e., receives) and handles an exception:
• Begins with keyword catch
• Exception parameter in parentheses – exception parameter identifies the
exception type and enables catch block to interact with caught exception
object
• Block of code in curly braces that executes when exception of proper type
occurs
12
Common Programming Errors
13
Termination Model of Exception Handling
• When an exception occurs:
• try block terminates immediately
• Program control transfers to first matching catch block
14
Example (2)
• When a Java program performs an illegal operation (division by
zero, access an array at a position which does not exist, etc.) an
event known as exception happens. When an exception occurs,
we say an exception is thrown.
}
catch (InputMismatchException e)
{
}
} 16
Example (2)
import java.util.InputMismatchException; Please enter the numerator:
import java.util.Scanner; r
public class Main { Error!!
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num=0;
System.out.println("Please enter the numerator:");
while (true) {
try
{
num = scan.nextInt();
System.out.println("The numerator is: " + num);
break;
}
catch (InputMismatchException e)
{
System.err.println("Error!!");
scan.next();
}
} 17
Example (2)
import java.util.InputMismatchException; Please enter the numerator:
import java.util.Scanner; r
public class Main { Error!! please enter the numerator:
public static void main(String[] args) { 2
Scanner scan = new Scanner(System.in); The numerator is: 2
int num=0;
System.out.println("Please enter the numerator:");
while (true) {
try
{
num = scan.nextInt();
System.out.println("The numerator is: " + num);
break;
}
catch (InputMismatchException e)
{
System.err.println("Error!! please enter the numerator: ");
scan.next();
}
} 18
Example (2)
Please enter the denominator:
System.out.println("Please enter the denominator:"); t
int deno; Error!! please enter the denominator:
while (true) { 0
0 not allowed as denominator!! Please enter the
try { denominator:
4
The denominator is:4
The result is : 0.5
}
catch (ArithmeticException ae)
{
}
catch (InputMismatchException e)
{
}
}
}
} 19
Example (2)
Please enter the denominator:
System.out.println("Please enter the denominator:"); t
int deno; Error!! please enter the denominator:
while (true) { 0
0 not allowed as denominator!!
try { Please enter the denominator:
deno = scan.nextInt(); 4
double result= num / deno; The denominator is:4
System.out.println("The denominator is:" + deno); The result is : 0.5
System.out.println("The result is : "+ (double) num / deno);
break;
}
catch (ArithmeticException ae)
{
System.err.println("0 not allowed as denominator!! \nPlease enter the denominator: ");
scan.nextLine();
}
catch (InputMismatchException e)
{
System.err.println("Error!! please enter the denominator: ");
scan.nextLine();
}
}
} 20
}
Example (3)
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try
{
int a[]=new int[10];
ArrayIndexOutOfBoundsException
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println ("ArrayIndexOutOfBounds");
}
}
}
}
21
finally Block
• If no exception occurs, catch blocks are skipped and control
proceeds to finally block.
22
finally Block
• If exception occurs in the try block, program skips rest of the
try block.
• First matching the catch block executes and control proceeds to the
finally block.
• If exception occurs and there are no matching catch blocks, control
proceeds to the finally block.
• After the finally block executes, the program passes the exception
to the next outer the try block.
• If catch block throws an exception, the finally block still
executes.
23
Execution
finally block in Java can be used to
put "cleanup" code such as closing a
file, closing connection, etc.
Typically contains resource-release
code
25
Try-Catch-Finally: tracing program execution (1)
26
Try-Catch-Finally: tracing program execution (1)
27
Try-Catch-Finally: tracing program execution (1)
28
Try-Catch-Finally: tracing program execution(2)
29
Try-Catch-Finally: tracing program execution(2)
30
Try-Catch-Finally: tracing program execution(2)
31
Try-Catch-Finally: tracing program execution(2)
32
Try-Catch-Finally: tracing program execution(3)
33
Try-Catch-Finally: tracing program execution(3)
34
Try-Catch-Finally: tracing program execution(3)
35
Try-Catch-Finally: tracing program execution(3)
//
System.out.println("\nRest of code to be executed...");
//
37
Example (5)-a
try
java.lang.NullPointerException: Cannot
{
invoke "String.length()" because "s" is null
String s = null;
System.out.println(s.length());
finally block is always executed
}
catch(NullPointerException e)
Rest of code to be executed...
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
//
System.out.println("Rest of code to be executed...");
//
38
Example (5)-b
try
NullPointerException
{
String s = null;
finally block is always executed
System.out.println(s.length());
}
Rest of code to be executed...
catch(NullPointerException e)
{
System.out.println("NullPointerException");
}
finally
{
System.out.println("finally block is always executed");
}
//
System.out.println("Rest of code to be executed...");
//
39
Using the throws Clause
• throws clause – specifies the exceptions a
method may throws
• Appears after method’s parameter list and before the
method’s body
• Contains a comma-separated list of exceptions
• Exceptions can be thrown by statements in method’s
body of by methods called in method’s body
• Exceptions can be of types listed in throws clause or
subclasses
40
Example (6)
41
Example (6) try block attempts to read input and
perform division
20 do
21 {
Retrieve input;
22 try // read two numbers and calculate quotient
InputMismatchException
23 {
thrown if input not valid integers
24 System.out.print( "Please enter an integer numerator: " );
25 int numerator = scanner.nextInt();
26 System.out.print( "Please enter an integer denominator: " ); Exception parameters
27 int denominator = scanner.nextInt();
28
29 int result = quotient( numerator, denominator );
30 System.out.printf( "\nResult: %d / %d = %d\n", numerator,
31 denominator, result ); Catching InputMismatchException
32 continueLoop = false; // input successful; end looping
(user has entered non-integer input)
33 } // end try
34 catch ( InputMismatchException inputMismatchException )
35 {
36 System.err.printf( "\nException: %s\n", Read invalid input but do nothing with it
37 inputMismatchException );
38 scanner.nextLine(); // discard input so user can try again
39 System.out.println(
40 "You must enter integers. Please try again. \n" ); Notify user of error made
41 } // end catch
42 catch ( ArithmeticException arithmeticException )
43 {
Catching ArithmeticException
44 System.err.printf( "\nException: %s\n", arithmeticException );
45 System.out.println( (user has entered zero for
46 "Zero is an invalid denominator. Please try again. \n" ); denominator)
47 } // end catch
48 } while ( continueLoop ); // end do...while
49 } // end main
50 } // end class DivideByZeroWithExceptionHandling 42
Example (6)
Please enter an integer numerator: 100
Please enter an integer denominator: 7
Result: 100 / 7 = 14
Result: 100 / 7 = 14
Exception: java.util.InputMismatchException
You must enter integers. Please try again.
Result: 100 / 7 = 14
43
Java Exception Hierarchy
• catch block catches all exceptions of its type and
subclasses of its type
• If there are multiple catch blocks that match a
particular exception type, only the first matching
catch block executes
• It makes sense to use a catch block of a
superclass when all the catch blocks for that
class’s subclasses will perform the same
functionality
44
Throwing Exceptions Using the throw Statement
45
Example (7)
public class Main {
public static void main(String[] args) {
try
{
throw new Exception();
}
catch (Exception e)
{
System.out.println("Exception occurred: " + e);
}
//
System.out.println("rest of the code to be executed...");
//
}
Exception occurred: java.lang.Exception
}
rest of the code to be executed...
46
Declaring New Exception Types
• You can declare your own exception classes that are
specific to the problems that can occur when another
program uses your reusable classes
• New exception class must extend an existing exception
class
• Typically contains only two constructors
– One takes no arguments, passes a default exception
messages to the superclass constructor
– One that receives a customized exception message as a
string and passes it to the superclass constructor
50
Assertions
• Assertions are conditions that should be true at a
particular point in a method
• Help ensure a program’s validity by catching
potential bugs
• Preconditions and Postconditions are two kinds of
assertions
• Assertions can be stated as comments or assertions
can be validated programmatically using the
assert statement
51
Assertions
• assert statement
• Evaluates a boolean expression and determines whether it is
true or false
• Two forms
• assert expression; -- AssertionError is thrown if expression is
false
• assert expression1 : expression2; -- AssertionError is
thrown if expression1 is false, expression2 is error message
• Used to verify intermediate states to ensure code is working
correctly
• Used to implement preconditions and postconditions
programmatically
• By default, assertions are disabled
• Assertions can be enabled with the –ea command-line
option (also see configuration in Eclipse shared in a previous
lab document)
52
Example
1 // Fig. 13.9: AssertTest.java
2 // Demonstrates the assert statement
3 import java.util.Scanner;
4
5 public class AssertTest
6 {
7 public static void main( String args[] )
8 {
assert statement
9 Scanner input = new Scanner( System.in );
10
11 System.out.print( "Enter a number between 0 and 10: " );
12 int number = input.nextInt();
Message to be displayed with
13 AssertionError
14 // assert that the absolute value is >= 0
15 assert ( number >= 0 && number <= 10 ) : "bad number: " + number;
16
17 System.out.printf( "You entered %d\n", number ); If number is less than 0 or greater than
18 } // end main 10, AssertionError occurs
19 } // end class AssertTest
54