Object - Oriented Programming
Object - Oriented Programming
Lab #09
Exception
• An exception represents an error condition that can occur during
the normal course of program execution
2
Introduction to Exception Handling
• Java library software (or programmer-defined code) provides a
mechanism that signals when something unusual happens
– This is called throwing an exception
3
Not Catching Exceptions
Scanner scanner = new Scanner(System.in);
System.out.println(“Enter integer:");
int number = scanner.nextInt();
What would happen if the user enters a value such as the test ‘ten’ instead
of 10?
4
Not Catching Exceptions (Contd)
• Two things occurred in this scenario
– Java threw an exception named InputMismatchException
– Our program failed to catch the exception resulting in a crash
5
try-throw-catch Basics
try {
6
Catching an Exception
System.out.print(prompt);
try {
7
try-catch Control Flow
Exception No Exception
try { try {
<t-stmt-1> <t-stmt-1>
Assume <t-stmt-3>
<t-stmt-2> throws an exception. <t-stmt-2> All statements in
the try block are
<t-stmt-3> <t-stmt-3> executed.
<t-stmt-4> Remaining statements <t-stmt-4>
. . . in the try block is . . .
<t-stmt-n> skipped.
<t-stmt-n>
} }
And the execution
<next stmt> continues to the <next stmt>
next statement
8
try-catch
9
try-catch (Contd)
• getMessage() method
– Every exception has a String instance variable that contains some
message, which typically identifies the reason for the exception
– The getMessage() returns the detail message string
10
Exception Object
• The two most important things about an exception object are its
type (i.e., exception class) and the message it carries
– The message is sent along with the exception object as an instance
variable
– This message can be recovered with the accessor method getMessage(),
so that the catch block can use the message
11
Exception Class
• Numerous predefined exception classes are included in the
standard packages that come with Java
– For example:
• IOException
• NoSuchMethodException
• FileNotFoundException
– Many exception classes must be imported in order to use them
• import java.io.IOException
12
Exception Message type
• An exception class can carry messages of any type
• An exception class constructor can be defined that takes an
argument of another type
– It would stores its value in an instance variable
– It would need to define accessor methods for this instance variable
13
Programmer-defined Exceptions
• Exception classes may be programmer-defined, but every such
class must be a derived class of an already existing exception
class
• The class Exception can be used as the base class, unless another
exception class would be more suitable
• At least two constructors should be defined, sometimes more
• The exception class should allow for the fact that the method
getMessage() is inherited
14
Programmer-defined Exceptions (Contd)
Public class MyException extends Exception{
// variables
public MyException(){
super("default message");
//perform other tasks
}
15
Preserve getMessage
• For all predefined exception classes, getMessage() returns the
string that is passed to its constructor as an argument
– Or it will return a default string if no argument is used with the
constructor
• This behavior must be preserved in all programmer-defined
exception class
– A constructor must be included having a string parameter whose body
begins with a call to super
– The call to super must use the parameter as its argument
– A no-argument constructor must also be included whose body begins
with a call to super
– This call to super must use a default string as its argument
16
Example
17
Multiple catch Blocks
• A single try-catch statement can include multiple catch blocks,
one for each type of exception
try {
…
age = scanner.nextInt();
…
val = cal.get(id); //cal is a GregorianCalendar
…
} catch (InputMismatchException e){
…
} catch (ArrayIndexOutOfBoundsException e){
…
}
18
Multiple catch Control Flow
Exception No Exception
try { Assume <t-stmt-3> try {
throws an exception
<t-stmt-1> and <catch-block-3> <t-stmt-1>
<t-stmt-2> is the matching block. <t-stmt-2> All statements in
the try block are
<t-stmt-3> <t-stmt-3> executed and throw
<t-stmt-4> Remaining statements <t-stmt-4> no exceptions.
. . . in the try block is . . .
skipped.
<t-stmt-n> <t-stmt-n>
} }
<catch-block-1> <catch-block-1>
<catch-block-2> Statements in <catch-block-2> All catch
the matching blocks are
<catch-block-3> <catch-block-3> skipped.
catch block
. . . are executed. . . .
<catch-block-m> <catch-block-m>
} }
<next stmt> <next stmt>
19
Important
• When using multiple catch statements always catch the more
specific exceptions first
catch (Exception e)
{…}
catch (NegativeNumberException e)
{…}
• Because a NegativeNumberException is a type of Exception, all
NegativeNumberExceptions will be caught by the first catch block
before ever reaching the second block
– The catch block for NegativeNumberException will never be used!
20
The finally Block
• There are situations where we need to take certain actions
regardless of whether an exception is thrown or not
• We place statements that must be executed regardless of
exceptions in the finally block
21
try-catch-finally Control Flow
Exception No Exception
try { Assume <t-stmt-i> try {
throws an exception
<t-stmt-1> and <catch-block-i> is
<t-stmt-1>
. . . the matching block. . . .
<t-stmt-i> <t-stmt-i>
. . . . . .
<t-stmt-n> <t-stmt-n>
} }
<catch-block-1> <catch-block-1>
. . . . . .
<catch-block-i> <catch-block-i>
. . . . . .
<catch-block-m> <catch-block-m>
} finally { } finally {
. . . finally block is . . . finally block is
} executed. } executed.
<next stmt> <next stmt>
22
Self-Test (1)
• 프로젝트 명: Project09_1
– git commit –m “Project09_1”
– 당일 밤 12시까지 제출
• Exception 클래스인 PowerFailureException 클래스를 정의할 것
– 음수값을 입력하면 발생하는 exception
– 인자가 없는 생성자를 지녀야 함
– 해당 생성자를 통해 exception이 발생할 경우 getMessage() 메소드는
“Power Failure”를 반환해야 함
– 하나의 String type 인자를 가지는 생성자를 지녀야 함
– 해당 생성자를 통해 exception이 발생할 경우 getMessage() 메소드는 생성자의 인자
로 사용된 값을 반환함
• Exception 클래스인 TooMuchStuffException 클래스를 정의할 것
– 10 이상의 숫자를 입력하면 발생하는 exception
– 인자가 없는 생성자를 지녀야 함
– 해당 생성자를 통해 exception이 발생할 경우 getMessage() 메소드는 “Too much
stuff!”를 반환해야 함
– 하나의 int type 인자를 가지는 생성자를 지녀야 함
– 해당 생성자를 통해 exception이 발생할 경우 getNumber() 메소드는 생성자의 인자
로 사용된 값을 반환함
23
Self-Test (1) (Contd)
24
Propagating Exceptions
• Instead of catching a thrown exception by using the try-catch
statement, we can propagate the thrown exception back to the
caller of our method
• The method header includes the reserved word throws
– This means somewhere in this code an exception can occur
– If it occurs this method will not deal with it
public int getAge( ) throws InputMismatchException {
. . .
int age = scanner.nextInt( );
. . .
return age;
}
25
Propagating Exceptions
• Instead of handling the exception this method has decided to
throw the exception as well. {someone else will handle it}
• The exception is propagated up the call stack as the caller may
also throw the exception to its caller
• Note:
– At some point the exception should be caught and handled
– The exception cannot be avoided indefinitely
– Therefore there must be some method that can handle the exception or
a crash may occur
26
Throwing Exceptions
• We can write a method that throws an exception directly, i.e., this
method is the origin of the exception
• Use the throw reserved to create a new instance of the exception
or its subclasses
• The method header includes the reserved word throws
27
‘throws’ keyword
28
Exception Types
• All types of thrown errors are instances of the Throwable class or
its subclasses
• Serious errors are represented by instances of the Error class or
its subclasses
• Exceptional cases that common applications should handle are
represented by instances of the Exception class or its subclasses
29
Exception Types
30
Catch or Declare Rule
• Most ordinary exceptions might be thrown within a method must
be accounted for in one of two ways:
1. The code that can throw an exception is placed within a try block, and
the possible exception is caught in a catch block within the same
method
2. The possible exception can be declared at the start of the method
definition by placing the exception class name in a throws clause
31
Catch or Declare Rule (Contd)
• The first technique handles an exception is a catch block
• The second technique is a way to shift the exception handling
responsibility to the method that invoked the exception throwing
method
• The invoking method must handle the exception, unless it too
uses the same technique to “pass the buck”
32
Catch or Declare Rule (Contd)
• In any one method, both techniques can be mixed
– Some exceptions may be caught, and others may be declared in a
throws clause
• However, these techniques must be used consistently with a
given exception
– If an exception is not declared, then it must be handled within the
method
– If an exception is declared, then the responsibility for handling it is
shifted to some other calling method
– Note that if a first method definition encloses an invocation of a second
method, and the second method can thrown an exception and does not
catch it, then the first method must catch or declare it
33
Checked and Unchecked Exceptions
• Exceptions that are subject to the catch or declare rule are called
checked exceptions
– The compiler checks to see if they are accounted for with either a catch
block or a throws clause
– The classes Throwable, Exception, and all descendants of the class
Exception are checked exceptions (Except RuntimeException and Derived
classes of it)
• All other exceptions are unchecked exceptions
• The class Error and all its descendant classes are called error
classes
– Error classes are not subject to the Catch or Declare rule
34
Exceptions to the rule
• Checked exceptions must follow the Catch or Declare rule
– Programs in which these exceptions can be thrown will not compile until
they are handled properly
• Unchecked exceptions are exempt from the Catch or Declare Rule
– Programs in which these exceptions are thrown simply need to be
corrected, as they result from some sort of error
35
Exceptions and Inheritance
• When a method in a derived class is overridden, it should have
the same exception classes listed in its throws clause that it had
in the base class
– Or it should have a subset of them
• A derived class may not add any exceptions to the throws clause
– But it can delete some
36
When to use Exceptions
• Exceptions should be reserved for situations where a method
encounters an unusual or unexpected case that cannot be
handled easily in some other way
• When exception handling must be used, here are some basic
guidelines:
– Include throw statements and list the exception classes in a throws
clause within a method definition
– Place the try and catch blocks in a different method
37
When to use Exceptions (Contd)
• Here is an example of a method from which the exception
originates:
38
When to use Exceptions (Contd)
• When someMethod is used by an otherMethod, the otherMethod
must then deal with the exception:
public void otherMethod()
{
try
{
someMethod();
…
}
catch(SomeException e)
{
CodeToHandleException
}
…
}
39
Exception Controlled Loops
• Sometimes it is better to simply loop through an action again
when an exception is thrown, as follows:
boolean done = false;
while(!done)
{
try
{
CodeThatMayThrowAnException
done = true;
}
catch (SomeExceptionClass e)
{
SomeMoreCode
}
}
40
Exception Controlled Loops
41
Exception Controlled Loops (Contd)
42
Exception Controlled Loops (Contd)
43
Exception Example
44
Self-Test (2)
• 프로젝트 명: Project09_2
– git commit –m “Project09_2”
– 당일 밤 12시까지 제출
• Exception을 발생시키는 ExceptionDemo 클래스를 작성할 것
– ExceptionDemo 클래스에는 사용자로부터 정수 값을 받는 main 메소드와 입력 값에
따라 exception을 발생시키는 메소드인 exerciseMethod가 있음
– ExceptionDemo 프로그램을 수행 시 다음과 같이 출력되도록 ExceptionDemo,
NegativeNumberException, PositiveNumberException 클래스를 수정할 것
• 입력 값: 양의 정수 • 입력 값: 0
In finally block No Exception
This number is positive! In finally block
Exception is caught in main After finally block
• 입력 값: 음의 정수 • 입력 값: 808
This number is negative! End of loop
Exception is caught in exerciseMethod
In finally block
After finally block
45
Self-Test (2) (Contd)
• 양수를 입력할 경우 PositiveNumberException 발생
– 해당 예외를 발생시킬 때 getMessage()를 통해 출력하고자 하는 문자열을
인자로 전달
– exerciseMethod는 해당 예외를 main method로 propagate 함.
– main method는 propagate 받은 메소드를 처리해야 함.
46
Self-Test (2) (Contd)
• PositiveNumberException 프로그래머 정의 exception 클래스
– Exception 클래스를 extends
– 프로그래머 정의 exception 클래스 권고 사항에 따라 2개의 생성자를 작성
해야 함
– 문자열 인자를 가진 생성자를 통해 문자열을 Exception 클래스에 전달
– ExceptionDemo 클래스에서 해당 문자열을 getMessage() 메소드를 통해 출
력
• NegativeNumberException 프로그래머 정의 exception 클래스
– Exception 클래스를 extends
– 프로그래머 정의 exception 클래스 권고 사항에 따라 2개의 생성자를 작성
해야 함
– 인자가 없는 생성자를 통해 문자열을 Exception 클래스에 전달
– ExceptionDemo 클래스에서 해당 문자열을 getMessage() 메소드를 통해 출
력
47
Self-Test (2) (Contd)
• 프로그램 수행 예시
48