0% found this document useful (0 votes)
4 views51 pages

06 Exceptions

This document discusses exception handling in Java, including types of errors such as syntax, run-time, and logic errors. It explains the use of try, catch, and finally blocks for managing exceptions, along with the distinction between checked and unchecked exceptions. Additionally, it provides examples of handling exceptions in Java programs to enhance robustness and fault tolerance.

Uploaded by

adam-diab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views51 pages

06 Exceptions

This document discusses exception handling in Java, including types of errors such as syntax, run-time, and logic errors. It explains the use of try, catch, and finally blocks for managing exceptions, along with the distinction between checked and unchecked exceptions. Additionally, it provides examples of handling exceptions in Java programs to enhance robustness and fault tolerance.

Uploaded by

adam-diab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

CSC 245

Objects and Data Abstraction


Topic 6 – Exception Handling

Dr. Rasha Alkhansa

Credits: the lecture slides are adapted from Dr.


Nadine Abbas and Dr. Khaleel Merchad lectures
Outline
• Syntax Errors
• Run-time Errors
• Logic Errors
• Exception-Handling
• try, throw and catch to detect, indicate and handle
exceptions, respectively
• finally block
• Java Exception Hierarchy
• Declaring new Exception Types
• Assertions

2
Syntax Errors
• Syntax errors are mistakes in the grammar of a
language

• The Java compiler detects syntax errors during


compilation and requires you to correct them before
successfully compiling the program

• Some common syntax errors include:


– Omitting or misplacing braces
– Invoking an instance method not defined
– Not declaring a variable before using it
– Providing multiple declarations of a variable
– Performing an incorrect type of operation on a primitive type
value

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)

Please enter an integer numerator: 100


Please enter an integer denominator: 7
ArithmeticException
Result: 100 / 7 = 14

Please enter an integer numerator: 100


Please enter an integer denominator: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at
DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoExceptionHandling.java:10)
at
DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:22)

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

• Uncaught exception – an exception that occurs for which there are no


matching catch blocks
• Cause program to terminate if program has only one thread; Otherwise only
current thread is terminated and there may be adverse effects to the rest of the
program

12
Common Programming Errors

•It is a syntax error to place code between a try


block and its corresponding catch blocks.

•Each catch block can have only a single


parameter—specifying a comma-separated list of
exception parameters is a syntax error.

13
Termination Model of Exception Handling
• When an exception occurs:
• try block terminates immediately
• Program control transfers to first matching catch block

• After exception is handled:


• Termination model of exception handling – program
control does not return to the throw point because the
try block has expired; Flow of control proceeds to the
first statement after the last catch block
• Resumption model of exception handling – program
control resumes just after throw point

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.

• Write a Java program that takes two integers, divides them by


each other
This program can potentially throw:
• an InputMismatchException if the user provides invalid
input
• an ArithmeticException in case of division by zero

To avoid program termination, we have the option to handle


these exceptions using try-catch
15
Example (2)
import java.util.InputMismatchException; Please enter the numerator:
import java.util.Scanner; r
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num;
System.out.println("Please enter the numerator:");
while (true) {
try
{

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

• After the finally block executes control proceeds to first


statement after the 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.

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

Source Flowchart: https://www.javatpoint.com/finally-block-in-exception-handling 24


finally Block
• Programs that obtain certain resources must return them
explicitly to avoid resource leaks
• finally block
– Consists of finally keyword followed by a block of code enclosed
in curly braces
– Optional in a try statement
– If present, is placed after the last catch block
– Executes whether or not an exception is thrown in the
corresponding try block or any of its corresponding catch blocks
– Will not execute if the application exits early from a try block via
method System.exit
– 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)

Nest statement won’t be reached 36


Example (4)
try
{ 3
String s = "Bob" ; finally block is always executed
System.out.println(s.length());
}
catch(NullPointerException e) Rest of code to be executed...
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed\n");
}

//
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)

1 // Fig. 13.2: DivideByZeroWithExceptionHandling.java


2 // An exception-handling example that checks for divide -by-zero.
3 import java.util.InputMismatchException;
4 import java.util.Scanner;
5 throws clause specifies that method
6 public class DivideByZeroWithExceptionHandling quotient may throw an
7 { ArithmeticException
8 // demonstrates throwing an exception when a divide -by-zero occurs
9 public static int quotient( int numerator, int denominator )
10 throws ArithmeticException
11 {
12 return numerator / denominator; // possible division by zero
13 } // end method quotient
14
15 public static void main( String args[] )
16 {
17 Scanner scanner = new Scanner( System.in ); // scanner for input
18 boolean continueLoop = true; // determines if more input is needed
19

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

Please enter an integer numerator: 100


Please enter an integer denominator: 0

Exception: java.lang.ArithmeticException: / by zero


Zero is an invalid denominator. Please try again.

Please enter an integer numerator: 100


Please enter an integer denominator: 7

Result: 100 / 7 = 14

Please enter an integer numerator: 100


Please enter an integer denominator: hello

Exception: java.util.InputMismatchException
You must enter integers. Please try again.

Please enter an integer numerator: 100


Please enter an integer denominator: 7

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

• throw statement – used to throw exceptions


• Programmers can throw exceptions themselves
from a method if something has gone wrong
• throw statement consists of keyword throw
followed by the exception object

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

• Examples and exercises will be given in the lab


sessions

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

Enter a number between 0 and 10: 5


You entered 5

Enter a number between 0 and 10: 50


Exception in thread "main" java.lang.AssertionError: bad number: 50
at AssertTest.main(AssertTest.java:15) 53
End of Topic 6

54

You might also like