Tải bản đầy đủ (.ppt) (53 trang)

Java C5. Exception Handling doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (763.9 KB, 53 trang )

1
Chapter 5. Exception Handling
ITSS Java Programming
CAO Tuan-Dung, HUT
2
What is an exception?

Exceptional event

Error that occurs during runtime

Cause normal program flow to be disrupted

Examples

Divide by zero errors

Accessing the elements of an array beyond
its range

Invalid input

Hard disk crash

Opening a non-existent file

Heap memory exhausted
3
Example
// divide by zero
class DivByZero {


public static void main(String args[]) {
System.out.println(3/0);
System.out.println(“Pls. print me.”);
}
}
// array out of bound
int array[] = new int[2];
array[0] = 1;
array[1] = 2;
array[2] = 3;
// execute method of object that does not exist
String s = null;
s.length();
Exception Object
ArithmeticException
Exception Object
ArrayIndexOutOfBoundException
Exception Object
NullPointerException
4
Default exception handling

Displays this error message Exception in thread
"main" java.lang.ArithmeticException: / by zero
at DivByZero.main(DivByZero.java:3)

Default exception handler

Provided by Java runtime


Prints out exception description

Prints the stack trace

Hierarchy of methods where the exception occurred

Causes the program to terminate
5
What Happens When an Exception
Occurs?

When an exception occurs within a method, the method
creates an exception object and hands it off to the runtime
system

Creating an exception object and
handing it to the runtime system is
called “throwing an exception”

Exception object contains
information about the error,
including its type and the state of
the program when the error occurred
6
Lab: Exception

Run this program and observe the exceptions exceptions of
the type that is different according to the specified value.
prompt> java Exceptions <ExceptionNO>
ExceptionNO:1→ArrayIndexOutOfBoundsEx

ception
ExceptionNO:2→NullPointerException
ExceptionNO:3→ArithmeticException
7
Exception.java
class Exceptions {
public static void main(String args[])throws Exception {
if(args.length != 1) {
System.out.println("Usage : java Exceptions <ExceptionNO>");
System.out.println("ExceptionNO:1→ArrayIndexOutOfBoundsException");
System.out.println("ExceptionNO:2→NullPointerException");
System.out.println("ExceptionNO:3→ArithmeticException");
System.exit(1);
}
int exceptionNo = Integer.parseInt( args[0] );
// Generate exception that is different according to the input value
switch(exceptionNo) {
case 1:
// ArrayIndexOutOfBoundsException
int array[] = new int[3];
array[3] = 100;
break;
8
Exception.java
case 2:
// NullPointerException
String s = null;
int length = s.length();
break;
case 3:

// ArithmeticException
int x = 100;
int y = 0;
int z = x / y;
break;
default:
System.out.println(“It doesn‘t match with ExceptionNO.");
}
}
}
9
System exceptions

Exceptions provided by Java language
10
Exception handling

To handle an exception in a program, the line that
throws the exception is executed within a try block

A try block is followed by one or more catch clauses

Each catch clause has an associated exception
type and is called an exception handler

When an exception occurs, processing continues at
the first catch clause that matches the exception
type
11
Exception handling

Syntax:
try {
<code to be monitored for exceptions>
} catch (<ExceptionType1> <ObjName>) {
<handler if ExceptionType1 occurs>
}

} catch (<ExceptionTypeN> <ObjName>) {
<handler if ExceptionTypeN occurs>
}
12
Example

This program shows how the exceptions in previous
example are caught and processed.

Usage:
prompt> java ExceptionsTryCatch <ExceptionNO>
ExceptionNO:1→ArrayIndexOutOfBoundsException
ExceptionNO:2→NullPointerException
ExceptionNO:3→ArithmeticException
13
ExceptionsTryCatch.java
class ExceptionsTryCatch {
public static void main(String args[])throws Exception {
if(args.length != 1) {
System.out.println("Usage : java Exceptions <ExceptionNO>");
System.out.println("ExceptionNO:1→ArrayIndexOutOfBoundsException");
System.out.println("ExceptionNO:2→NullPointerException");
System.out.println("ExceptionNO:3→ArithmeticException");

System.exit(1);
}
int exceptionNo = Integer.parseInt( args[0] );
try {
// Generate exception that is different according to the input value
switch(exceptionNo) {
case 1:
// ArrayIndexOutOfBoundsException
int array[] = new int[3];
array[3] = 100;
break;
14
ExceptionsTryCatch.java
case 2:
// NullPointerException
String s = null;
int length = s.length();
break;
case 3:
// ArithmeticException
int x = 100;
int y = 0;
int z = x / y;
break;
default:
System.out.println(“It doesn‘t match with ExceptionNO.");
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(“ArrayIndexOutOfBoundsException is caught .");
}catch(NullPointerException e){

System.out.println(“NullPointerException is caught.");
catch(ArithmeticException e){
System.out.println(“ArithmeticException is caught.");
}
}
}
15
User definition Exception

Classes that define exceptions are related by
inheritance, forming an exception class hierarchy

All error and exception classes are descendents of
the Throwable class

A programmer can define an exception by
extending the Exception class or one of its
descendants

The parent class used depends on how the new
exception will be used
16
User definition Exception
public class LimitException extends Exception{
// Constructor
public LimitException(String message){
super(message);
}
:// Addition of necessary attribute and method
}

Throwable
Exception
XXException
XX1Exception
XX2Exception
17
Error processing in User define exception

Flow of exception handling

Execute a processing that has the
possibility to generate an error.

A systematic or operational error
occurs.

An exception object is generated.

The exception object is notified,and
the error processing according to
the exception object is executed.
18
Error processing in User define exception
try {
obj.withdraw(10000000);
}
catch (LimitException e){

System.out.println(e.getMessage())
;

e.printStackTrace();
}
public void withdraw(long money) throws
LimitException, InsufficiencyException {
if (money>=1000000) throw new
LimitException (“Deposit amount limit is
exceeded);
}
(2) Error occurred.
E
x
c
e
p
t
i
o
n
Exception
Object
(1) Execute a processing that has
the possibility to generate an error.
(3) Exception object
is generated.
(4) Exception object is notified
and error processing is done.
19
Method that throws exception
[Modifier] Return value type Method name(Argument…) throws Exception Class, {
throw Exception Object

}
declare the exception type that
the method might throw.
generating Exception Object.
Exception handling in the caller of this method
public void withdraw(long money) throws LimitException, InsufficiencyException {
if (money>=1000000) throws new LimitException (“Deposit amount limit
is exceeded”);
if (money>balance) throws new InsufficiencyException (“Insufficient
balance”);
balance -=money;
}
20
Obtaining of error information

public String getMessage(): Return error message of the
exception object.

public void printStackTrace(): tells where is the origin of the
error in the program.
try {
obj.withdraw(10000000);
}
catch (LimitException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
21
Lab


Define two Exception classes LimitException,
InsufficiencyException and use them for error handling in the
Bank program. This program generates the object of
account class (Account), and withdraws the specified
amount. When the specified amount exceeds the balance or
the withdrawal limit is exceeded, the user definition
exception is generated.
Execution of exercise program
prompt> java Bank <id> <Balance> <Withdrawal
amount>
22
Solution: Bank.java
class Bank {
public static void main(String args[]) {
Account obj = null;
if(args.length != 3) {
System.out.println("Usage : java
Bank <id> <Balance>
<Withdrawal amount>");
System.exit(1);
}
try {
// Getting parameter
String id = args[0];
long initbalance =
Long.parseLong(args[1]);
long money =
Long.parseLong(args[2]);
// Generation of account object
obj = new Account(id ,

initbalance);
System.out.println("Initial display");
obj.print();

// Withdrawal of specified amount
obj.withdraw(money);
} catch(LimitException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch(InsufficiencyException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println(“Display of
Results");
obj.print();
}
}
}
23
Solution: Bank.java
// Account class
class Account {
private String id; // Account Number pg
private long balance; // Balance
// Constructor
public Account(String initId, long initBalance) {

id = initId;
balance = initBalance;
}
// Payment
public void withdraw(long money) throws
LimitException, InsufficiencyException {
if(money >= 1000000) {
throw new
LimitException(“Withdrawal amount
limit is exceeded");
}
if(money > balance) {
throw new
InsufficiencyException("Insufficient
balance");
}
balance -= money;
}

// Display of account information
public void print() {
System.out.println("ID : " + id);
System.out.println("Balance : " +
balance);
}
}
24
Solution: Bank.java
// Exception of exceeded withdrawal amount limit
class LimitException extends Exception {

public LimitException(String message) {
super(message);
}
}
// Insufficient balance exception
class InsufficiencyException extends Exception {
public InsufficiencyException(String message) {
super(message);
}
}
25
Wrapper Class

Some Facts:

Primitive data types are not objects

Cannot access methods of the Object class

Only actual objects can access methods of the
Object class

Why wrapper classes?

Need an object representation for the primitive
type variables to use Java built-in methods

Definition:

Object representations of simple non-object

variables

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×