0% found this document useful (0 votes)
9 views

CSC245 Lecture 7

The document provides an overview of exception handling in Java, detailing types of errors such as syntax, run-time, and logic errors. It explains how to use try and catch blocks to manage exceptions, the Java exception hierarchy, and the importance of declaring new exception types. Additionally, it discusses the use of finally blocks for resource management and the mechanics of throwing exceptions in Java programs.

Uploaded by

armajd676
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

CSC245 Lecture 7

The document provides an overview of exception handling in Java, detailing types of errors such as syntax, run-time, and logic errors. It explains how to use try and catch blocks to manage exceptions, the Java exception hierarchy, and the importance of declaring new exception types. Additionally, it discusses the use of finally blocks for resource management and the mechanics of throwing exceptions in Java programs.

Uploaded by

armajd676
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Exception Handling

02/19/2019 DIANA HAIDAR 1


Outline
 Syntax Errors
 Run-time Errors or Exceptions
 Logic Errors
 Introduction
 Exception Handling Overview
 Example: Divide by Zero without Exception Handling
 Example: Handling ArithmeticExceptions and InputMismatchExceptions
 When to use Exception Handling
 Java Exception Hierarchy
 Declaring New Exception Types
 finally block
 Assertions

02/19/2019 DIANA HAIDAR 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
 Performing an incorrect type of operation on a primitive type value
 Invoking an instance method not defined
 Not declaring a variable before using it
 Providing multiple declarations of a variable

02/19/2019 DIANA HAIDAR 3


Run-time Errors or Exceptions
 Run-time errors occur during program execution when the JVM detects an operation that it knows to be
incorrect, and cause the JVM to throw an exception.

02/19/2019 DIANA HAIDAR 4


Logic Errors
 A logic error occurs when the programmer or analyst makes a mistake in the design of a class or method
or implements an algorithm incorrectly.
 Most logic errors do not cause syntax or run-time errors and are thus difficult to find.
 Sometimes found through testing or during real-world operation of the program.

02/19/2019 DIANA HAIDAR 5


Introduction
 An exception is an indication of a problem that occurs during a program’s execution.
 Exception handling enables programmers to write robust and fault-tolerant programs that can resolve (or
handle) exceptions.
 Error prevention tip: Exception handling helps improve a program’s fault tolerance.
 Examples:
 ArrayIndexOutOfBoundsException -- occurs when an attempt is made to access an element past the
end of an array. Such a problem may occur if there is an “off-by-one” error in a for statement that
manipulates an array.
 ClassCastException -- occurs when an attempt is made to cast an object that does not have an is-a
relationship with the type specified in the cast operator.
 NullPointerException -- occurs whenever a null reference is used where an object is expected.

02/19/2019 DIANA HAIDAR 6


Exception Handling Overview

 Although this form of error handling works, intermixing program logic with error-handling logic can make
programs difficult to read, modify, maintain and debug—especially in large applications.
 Exception handling enables programmers to remove error-handling code from the “main line” of the
program’s execution, improving program clarity and enhancing modifiability.

02/19/2019 DIANA HAIDAR 7


Example: Divide by Zero without Exception Handling
1 // Fig. 13.1: DivideByZeroNoExceptionHandling.java
2 // An application that attempts to divide by zero.
 Exceptions are thrown (i.e. the exception 3 import java.util.Scanner;
occurs) when a method detects a problem and 4

is unable to handle it. 5


6
public class DivideByZeroNoExceptionHandling
{
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: " );
20 int denominator = scanner.nextInt();
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

Please enter an integer numerator: 100


Please enter an integer denominator: 7

Result: 100 / 7 = 14

02/19/2019 DIANA HAIDAR 8


Example: Divide by Zero without Exception Handling
 Stack trace – a descriptive message Please enter an integer numerator: 100
displayed in response to invalid input, Please enter an integer denominator: 7

which includes the name of the exception Result: 100 / 7 = 14


and the path of execution that led to the
exception method by method.
Please enter an integer numerator: 100
 This information helps in debugging a Please enter an integer denominator: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
program. at
DivideByZeroNoExceptionHandling.quotient(DivideByZeroNoExceptionHandling.java:10)
at
 ArithmeticException -- can arise from a DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:22)

number of different problems in


arithmetic.
Please enter an integer numerator: 100
 InputMismatchException -- occurs when Please enter an integer denominator: hello
Exception in thread "main" java.util.InputMismatchException
Scanner method nextInt receives a string at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
that does not represent a valid integer. at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
 Throw point—the initial point at which at
DivideByZeroNoExceptionHandling.main(DivideByZeroNoExceptionHandling.java:20)
the exception occurs.

02/19/2019 DIANA HAIDAR 9


Example: Handling ArithmeticExceptions and InputMismatchExceptions
 Uses exception handling so that if the user makes a mistake, the program catches and handles (i.e. deals
with) the exception allowing the user to try to enter the input again.

Enclosing Code in a try Block


 try block -- encloses the code that might throw an exception and the code that should not execute if an
exception occurs.
 If an exception occurs, the remaining code in the try block will be skipped.
 A try block consists of the keyword try followed by a block of code enclosed in curly braces ({ }).
Exceptions may surface
 through explicitly mentioned code in a try block,
 through calls to other methods,
 through deeply nested method calls initiated by code in a try block, or
 from the Java Virtual Machine as it executes Java bytecodes.

02/19/2019 DIANA HAIDAR 10


Example: Handling ArithmeticExceptions and InputMismatchExceptions
Catching Exceptions
 A catch block (also called a catch clause or exception handler) catches (i.e. receives) and handles an
exception.
 A catch block begins with the keyword catch and is followed by a parameter in parentheses (called the
exception parameter) and a block of code enclosed in curly braces ({ }).

02/19/2019 DIANA HAIDAR 11


Example: Handling ArithmeticExceptions and InputMismatchExceptions
1 // Fig. 13.2: DivideByZeroWithExceptionHandling.java 29 int result = quotient( numerator, denominator );
2 // An exception-handling example that checks for divide-by-zero.
30 System.out.printf( "\nResult: %d / %d = %d\n", numerator,
3 import java.util.InputMismatchException;
31 denominator, result );
4 import java.util.Scanner;
32 continueLoop = false; // input successful; end looping
5
33 } // end try
6 public class DivideByZeroWithExceptionHandling
34 catch ( InputMismatchException inputMismatchException )
7 {
8 // demonstrates throwing an exception when a divide-by-zero occurs
35 {
9 public static int quotient( int numerator, int denominator ) 36 System.err.printf( "\nException: %s\n",
10 throws ArithmeticException 37 inputMismatchException );
11 { 38 scanner.nextLine(); // discard input so user can try again
12 return numerator / denominator; // possible division by zero 39 System.out.println(
13 } // end method quotient 40 "You must enter integers. Please try again.\n" );
14 41 } // end catch
15 public static void main( String args[] ) 42 catch ( ArithmeticException arithmeticException )
16 { 43 {
17 Scanner scanner = new Scanner( System.in ); // scanner for input 44 System.err.printf( "\nException: %s\n", arithmeticException );
18 boolean continueLoop = true; // determines if more input is needed 45 System.out.println(
19 46 "Zero is an invalid denominator. Please try again.\n" );
20 do
47 } // end catch
21 {
48 } while ( continueLoop ); // end do...while
22 try // read two numbers and calculate quotient
49 } // end main
23 {
50 } // end class DivideByZeroWithExceptionHandling
24 System.out.print( "Please enter an integer numerator: " );
25 int numerator = scanner.nextInt();
26 System.out.print( "Please enter an integer denominator: " );
27 int denominator = scanner.nextInt();
28

02/19/2019 DIANA HAIDAR 12


Example: Handling ArithmeticExceptions and InputMismatchExceptions
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

02/19/2019 DIANA HAIDAR 13


Example: Handling ArithmeticExceptions and InputMismatchExceptions
 Each catch block specifies in parentheses an exception parameter that identifies the exception type the
handler can process.
 When an exception occurs in a try block, the catch block that executes is the one whose type matches the
type of the exception that occurred.
 The type in the catch block matches the thrown exception type exactly or is a superclass of it.
 If there are multiple catch blocks that match a particular exception type, only the first matching catch block
executes when an exception of that type occurs.
 For example, we could follow a catch block for type ArithmeticException with a catch block for type
Exception (superclass of ArithmeticException).

 An uncaught exception is an exception that occurs for which there are no matching catch blocks.
 Causes a program to terminate, if the program has only one thread.
 Terminates a only the thread where the exception occurred, if a program has multiple threads. There
may be adverse effects to the rest of the program.

02/19/2019 DIANA HAIDAR 14


Example: Handling ArithmeticExceptions and InputMismatchExceptions
 Common programming error: It is a syntax error to place code
between a try block and its corresponding catch blocks.
 Common programming error: Each catch block can have only a
single parameter.
 Specifying a comma-separated list of exception parameters is
a syntax error.

02/19/2019 DIANA HAIDAR 15


Example: Handling ArithmeticExceptions and InputMismatchExceptions
Termination Model of Exception Handling
 If an exception occurs in a try block, the try block terminates immediately and program control transfers
to the first of the following catch blocks in which the exception parameter’s type matches the thrown
exception’s type.
 After the exception is handled, program control does not return to the throw point because the try block
has expired (and its local variables have been lost).
 Control resumes to the first statement after the last catch block.
 Common programming error: Logic errors can occur if you assume that after an exception is handled,
control will return to the first statement after the throw point.

02/19/2019 DIANA HAIDAR 16


Example: Handling ArithmeticExceptions and InputMismatchExceptions
Using the throws Clause
 A throws clause specifies the exceptions the method throws.
 This clause appears after the method’s parameter list and before the method’s body.
 It contains a comma-separated list of the exceptions that the method will throw if a problem occurs.
 Such exceptions may be thrown by statements in the method’s body or by methods called from the body.

 Error prevention tip: If you know that a method might throw an exception, include appropriate exception-
handling code in your program to make it more robust.
 Exceptions are not required to be listed in a method’s throws clause -- even if they are, it is not required
that such exceptions be caught by an application.

02/19/2019 DIANA HAIDAR 17


When to use Exception Handling
 Exception handling is designed to process synchronous errors.
 Synchronous errors occur when a statement executes.
 Examples: out-of-range array indices, arithmetic overflow, division by zero, invalid method parameters,
thread interruption and unsuccessful memory allocation.
 Asynchronous events occur in parallel with, and independent of, the program’s flow of control.
 Examples: disk I/O completions, network message arrivals, mouse clicks and keystrokes.

02/21/2019 DIANA HAIDAR 18


Java Exception Hierarchy
 All Java exception classes inherit, either directly or indirectly, from class Exception, forming an inheritance
hierarchy.
 Programmers can extend this hierarchy to create their own exception classes.
 class Throwable is the superclass of class Exception.
 Only Throwable objects can be used with the exception-handling mechanism.
 Class Throwable has two subclasses:
 Class Exception and its subclasses represent exceptional situations that can occur in a Java program and
that can be caught by the application.
 Class Error and its subclasses represent abnormal situations that could happen in the JVM – It is usually
not possible for applications to recover from Errors.

02/21/2019 DIANA HAIDAR 19


Java Exception Hierarchy

02/21/2019 DIANA HAIDAR 20


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 message to the superclass constructor.
 One that receives a customized exception message as a string and passes it to the superclass
constructor.

02/21/2019 DIANA HAIDAR 21


finally block
 Programs that obtain certain types of resources must return them to the system explicitly to avoid
resource leaks.
 A finally block almost always executes, it typically contains resource-release code.
 The finally block consists of the finally keyword, followed by code enclosed in curly braces
 Is optional, and is sometimes referred to as the finally clause.
 If it is present, it is placed after the last catch block.
 A finally block will execute
 whether or not an exception is thrown in the corresponding try block or any of its corresponding
catch blocks.
 If a try block exits by using a return, break or continue statement.
 A finally block will not execute if the application exits early from a try block by calling method
System.exit.

02/21/2019 DIANA HAIDAR 22


finally block
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

02/21/2019 DIANA HAIDAR 23


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.
 The first matching catch block executes and control proceeds to the
finally block.
 If catch block throws an exception, the finally block still
executes.
 After the finally block executes, the program passes the
exception to the next outer try block.
 If there are no matching catch block, control proceeds to the finally
block .
 After the finally block executes, the program passes the
exception to the next outer the try block.

02/21/2019 DIANA HAIDAR 24


finally block
1
2 //

// Fig. 13.5: UsingExceptions.java
Demonstration of the try...catch...finally exception handling
21
22
// demonstrate try...catch...finally
public static void throwException() throws Exception
3 // mechanism. 23 {
4 24 try // throw an exception and immediately catch it
5 public class UsingExceptions 25 {
6 { 26 System.out.println( "Method throwException" );
7 public static void main( String args[] ) 27 throw new Exception(); // generate exception
8 { 28 } // end try
9 try 29 catch ( Exception exception ) // catch exception thrown in try
10 { 30 {
11 throwException(); // call method throwException 31 System.err.println(
12 } // end try 32 "Exception handled in method throwException" );
13 catch ( Exception exception ) // exception thrown by throwException 33 throw exception; // rethrow for further processing
14 { 34
15 System.err.println( "Exception handled in main" ); 35 // any code here would not be reached
16 } // end catch 36
17 37 } // end catch
18 doesNotThrowException(); 38 finally // executes regardless of what occurs in try...catch
19 } // end main 39 {
20 40 System.err.println( "Finally executed in throwException" );
41 } // end finally
42
43 // any code here would not be reached, exception rethrown in catch
44

02/21/2019 DIANA HAIDAR 25


finally block
45 } // end method throwException
46
 System.err (known as the standard error stream) 47 // demonstrate finally when no exception occurs
is used to display a program’s errors. 48 public static void doesNotThrowException()
49 {

 Can be displayed on the command prompt. 50


51
try // try block does not throw an exception
{
52 System.out.println( "Method doesNotThrowException" );
 Using two different streams (System.out and 53 } // end try
System.err) enables the programmer to easily 54 catch ( Exception exception ) // does not execute
55 {
separate error messages from other output. 56 System.err.println( exception );
57 } // end catch
58 finally // executes regardless of what occurs in try...catch
59 {
60 System.err.println(
61 "Finally executed in doesNotThrowException" );
62 } // end finally
63
64 System.out.println( "End of method doesNotThrowException" );
65 } // end method doesNotThrowException
66 } // end class UsingExceptions

Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
End of method doesNotThrowException

02/21/2019 DIANA HAIDAR 26


Assertions
 Assertions are conditions that should be true at 1
2
// Fig. 13.9: AssertTest.java
// Demonstrates the assert statement
a particular point in a method. 3 import java.util.Scanner;
4

 Assertions are primarily used by the 5


6
public class AssertTest
{
programmer for debugging and identifying logic 7 public static void main( String args[] )
errors in an application. 8 {
9 Scanner input = new Scanner( System.in );

 Preconditions and postconditions are two types 10


11 System.out.print( "Enter a number between 0 and 10: " );
of assertions. 12 int number = input.nextInt();

 Preconditions are assertions about a 13


14 // assert that the absolute value is >= 0
program’s state when a method is invoked. 15 assert ( number >= 0 && number <= 10 ) : "bad number: " + number;
16
 Postconditions are assertions about a 17 System.out.printf( "You entered %d\n", number );
program’s state after a method finishes. 18 } // end main
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)

02/21/2019 DIANA HAIDAR 27


Assertions
 Assertions can be stated as comments or assertions can be validated programmatically using the assert
statement.
 An assert statement evaluates a boolean expression and determines whether it is true or false.
Two forms
 assertionError is thrown if expression is false.
 assertionError is thrown if expression1 is false, expression2 is error
message.
 Used to verify intermediate states to ensure code is working correctly.
 By default, assertions are disabled and can be enabled with the –ea command-line option.

02/21/2019 DIANA HAIDAR 28

You might also like