1. Trang chủ
  2. » Công Nghệ Thông Tin

Java C5. Exception Handling doc

53 653 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Exception Handling in Java
Tác giả Cao Tuan-Dung
Trường học Hanoi University of Technology
Chuyên ngành Java Programming
Thể loại Giáo trình
Thành phố Hanoi
Định dạng
Số trang 53
Dung lượng 468,5 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 the runtime system is call

Trang 1

Chapter 5 Exception Handling

ITSS Java Programming CAO Tuan-Dung, HUT

Trang 2

What is an exception?

 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

Trang 3

// array out of bound

int array[] = new int[2];

Exception Object ArrayIndexOutOfBoundException

Exception Object NullPointerException

Trang 4

Default exception handling

"main" java.lang.ArithmeticException: / by zero

at DivByZero.main(DivByZero.java:3)

 Provided by Java runtime

 Prints out exception description

 Prints the stack trace

 Causes the program to terminate

Trang 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

the runtime system is called “throwing an

exception”

error, including its type and the state of the

program when the error occurred

Trang 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 ArrayIndexOutOfBoundsException →ArrayIndexOutOfBoundsException ExceptionNO:2 NullPointerException →ArrayIndexOutOfBoundsException

ExceptionNO:3 ArithmeticException →ArrayIndexOutOfBoundsException

Trang 7

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");→ArrayIndexOutOfBoundsException

System.out.println("ExceptionNO:2 NullPointerException");→ArrayIndexOutOfBoundsExceptionSystem.out.println("ExceptionNO:3 ArithmeticException");→ArrayIndexOutOfBoundsExceptionSystem.exit(1);

}int exceptionNo = Integer.parseInt( args[0] );

// Generate exception that is different according to the input valueswitch(exceptionNo) {

case 1:

// ArrayIndexOutOfBoundsException

int array[] = new int[3];

array[3] = 100;

Trang 8

}

Trang 9

System exceptions

 Exceptions provided by Java language

Trang 10

Exception handling

throws the exception is executed within a try block

 A try block is followed by one or more catch clauses

and is called an exception handler

the first catch clause that matches the exception

type

Trang 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>

Trang 12

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

 Usage:

prompt> java ExceptionsTryCatch <ExceptionNO>

ExceptionNO:1 ArrayIndexOutOfBoundsException →ArrayIndexOutOfBoundsException

ExceptionNO:2 NullPointerException →ArrayIndexOutOfBoundsException

ExceptionNO:3 ArithmeticException →ArrayIndexOutOfBoundsException

Trang 13

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"); →ArrayIndexOutOfBoundsException

System.out.println("ExceptionNO:2 NullPointerException"); →ArrayIndexOutOfBoundsException System.out.println("ExceptionNO:3 ArithmeticException"); →ArrayIndexOutOfBoundsException System.exit(1);

} int exceptionNo = Integer.parseInt( args[0] );

try { // Generate exception that is different according to the input value switch(exceptionNo) {

Trang 15

User definition Exception

inheritance, forming an exception class hierarchy

the Throwable class

extending the Exception class or one of its

descendants

exception will be used

Trang 16

User definition Exception

public class LimitException extends Exception{

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

 The exception object is notified,and the error

processing according to the exception object is executed.

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

Exce

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

Trang 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”);

Trang 20

Obtaining of error information

exception object.

the error in the program.

try { obj.withdraw(10000000);

}catch (LimitException e){

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

e.printStackTrace();

}

Trang 21

 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

Trang 22

Solution: Bank.java

class Bank {

public static void main(String args[]) {

Account obj = null;

// Generation of account object

obj = new Account(id ,

} 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();

}}

Trang 23

Solution: Bank.java

// Account class

class Account {

private String id; // Account Number pg

private long balance; // Balance

}}

Trang 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);

}

}

Trang 25

Wrapper Class

 Primitive data types are not objects

 Cannot access methods of the Object class

 Only actual objects can access methods of the Object

class

 Need an object representation for the primitive type

variables to use Java built-in methods

 Definition:

Object representations of simple non-object variables

Trang 26

Integer wrapper class

int i=100;

Integer intObj1 = new Integer(i);

String s= “12345”;

Integer intObj2 = Integer.valueOf(s);

static int parseInt(String str) Convert the character string into the value

of the ‘int’ type

static Integer valueOf(String str) Convert the character string specified with

‘str’ into the value of the ‘int’ type, and generate the ‘Integer’ object based on it.int intValue() Return the object's value by the value of

the ‘int’ type

double doubleValue() Return the object's value by the value of

the ‘double’ type

String toString() Return the object’s value by the string

expression Return the object s value by the string expression

Trang 27

 Variable length Array of pair

Key and value

 Iterator <E> inteface

 interface to obtain the

elements of collection while

:

Trang 28

Collection API interface and implement

class

Trang 29

 Function to relate a specific type to the general class and the method

 Definition of class using Generics

[Modifier] Class name <type parameter> { :

Trang 30

obj=param;

return obj;

}}

MyClass<String> mc = new MyClass<String>();

String rt= mc.func(“Hello”);

T is replaced by String type

Trang 31

Use of Generics

// Create HashMap with two type parameters

HashMap<String, Mammal> map =

new HashMap<String, Mammal>();

map.put(“wombat”, new

Mammal("wombat"));

Mammal w = map.get(“wombat”);

// Create a Vector of String type

Vector<String> vs = new Vector<String>();

vs.add(new Integer(5)); // Compile error!

vs.add(new String(“hello”));

Trang 32

Collection and Generics

 Objects other than the specified type cannot be added to the generated collection.

 Example: This vector can contain only string objects

Vector<String> vs = new Vector<String>();

Trang 33

Generics and Sub-typing

 You can't do this:

ArrayList<Object> ao = new ArrayList<Integer>();

 If it is allowed, ClassCastException can occur during runtime – this is not type-safe

ArrayList<Integer> ai = new ArrayList<Integer>();

ArrayList<Object> ao = ai; // If it is allowed at compile time, ao.add(new Object());

Integer i = ai.get(0); // This would result in // runtime ClassCastException

Trang 34

class ArrayList

 The ArrayList class is part of the java.util package

 Furthermore, an ArrayList object grows and shrinks as needed, adjusting its capacity as necessary

 Elements can be inserted or removed with a single method invocation

 When an element is inserted, the other elements "move

aside" to make room

 Likewise, when an element is removed, the list "collapses"

to close the gap

Trang 35

class ArrayList: Major constructor

 ArrayList(): Generate an empty ArrayList object.

 ArrayList(Collection<E> c): Generate an ‘ArrayList’ object that retains element of ‘Collection’ specified by ‘c’.

‘ArrayList’ object with initial capacity specified by

‘initialCapacity’.

1

0 2 3 4 5 6 … 26

ArrayList object

Trang 36

ArrayList: methods

interface of ArrayList

by o at the end of ‘ArrayList’ to return ‘true’.

the position specified with ‘index’ in ‘ArrayList’ to

return the deleted element.

position specified with ‘index’ in ‘ArrayList’.

Trang 37

HashMap<K,V> class

 Major constructors ‘HashMap<K V>’ class

object of initial capacity specified with

‘initialCapacity’.

HashMap<String, String> hm = new

HashMap<String, String>();

Trang 38

HashMap<k,v> class: methods

 int size(): Return the number of keys stored in

 V remove(Object key): Delete the element

corresponding to the key from ‘HashMap’

hm.put("key1", "Hello");

: String str = hm.get(“key1”);

Trang 39

Iterator<E> Interface

 boolean hasNext() : Return ‘true’ when there is still an

element in the repetition processing.

 E next() : Return the next element in the repetition

while(iter.hasNext()) { // Repeat while there is an element

System.out.println(iter.next()); // Take out the next element to display

Trang 40

Example: The use of ArrayList

 In this program, the object of product information class

(ItemInfo) is made and stored in ‘ArrayList’ Then, the

element is acquired from ‘ArrayList’ by using the method

and the iterator, and information on the element is output

to the standard output

Trang 41

import java.util.*;

public class UseArrayList{

public static void main(String args[]){

//ArrayList Object creation(Element that can be

stored is only ‘ItemInfo’ type)

al.add(new ItemInfo(“Ball-point pen", 100));

//Information display after taking out the element

Trang 42

// Product class

class ItemInfo{

private String name; // Product name

private int price; // Price

public ItemInfo(String name, int price){

this name name this.name = name;

this.price = price;

}

// Product information display

public void print(){

System.out.println(“Product name :” + name + ”

“¥tPrice :” " + price + “Yen");

}

}

Trang 43

Automatic type conversion

 Executes implicitly the type conversion

between basic data type and wrapper classes

Integer intObj = 100; // Auto boxing int x = new Integer(200);// Auto-unboxing

Trang 44

Lab: Exception handling

 Modify the program so that the errors can be caught and processed

 Image of error when running program

prompt> java Division 200 0 < - Divide by 0

Exception in thread "main" java.lang.ArithmeticException:

/ by zero at Division.main(Division.java:18)

prompt> java Division 50w 6 < - Input value that doesn’t become integer

Exception in thread "main" java.lang.NumberFormatException:

For input string: "50w"at java.lang.NumberFormatException

forInputString(NumberFormatException.java:48)

at java.lang.Integer.parseInt(Integer.java:456)

at java.lang.Integer.parseInt(Integer.java:497)

Trang 45

Current source code

class Division {

public static void main(String args[]) {

if(args.length != 2) {

System.out.println("Usage:java Division System.out.println( Usage:java Division

<Integer divided> <Integer to divide>");

Trang 46

Result expected

 Execution image of program to which

exception handling was added

prompt> java Division 200 0

0 is specified for number to divide with.

prompt> java Division 20w 6 ppj Impossible to make the input value an integer.

Trang 47

Lab: Find Employee

 There are two or more employee objects and

a manager objects that manages them The program requests the manager object to

search with the employee number as a key When it finds an employee who matches to the retrieval key, it returns this object When there is no employee who matches to the

retrieval key, it throws the user definition

exception.

Trang 48

Lab: Find Employee

 There are two or more employee objects and a manager objects that manages them The program requests the manager object to search with the employee number as a key When it finds an employee who matches to the retrieval key, it returns this object When there is no

employee who matches to the retrieval key, it throws the user definition exception.

EmployeeEmployeeEmployee

ManagerException

FindEmployee

findEmployee(Employee number)

Throw NotFoundException

Trang 49

Definition of class

 FindEmployee.java :” Application class

 Employee.java :” Employee information

class This class has been made.

 Manager.java :” Manager class This class has been made, but add a description that

throws an exception.

 NotFoundException.java :” Exception class This class is undefined Make it newly.

Trang 50

Your steps

‘NotFoundException.java’.

‘findEmployee()’ method of ‘Manager.java’,

modify so that it throw the

‘NotFoundException’ exception.

‘NotFoundException.java’, ‘Manager.java’ and

‘FindEmployee.java’

Trang 51

public class FindEmployee {

public static void main(String args[]) {

// Making of manager object

Manager mgr = new Manager();

if(args.length != 1) {

System.out.println ("Usage : java

FindEmployee <Employee number>");

} catch(Exception e) { e.printStackTrace();

} } }

Trang 52

public class Employee {

private int id; // ID

private String name; // Name

private String section; // Section

private String phone; // Extension

// Constructor

public Employee (int id, String name, String

section, String phone) {

} // Display methodpublic void print() { System.out.println("ID :" + id);

System.out.println("NAME :" + name); System.out.println("SECTION:" + section); System.out.println("PHONE :" + phone);}

}

Ngày đăng: 28/06/2014, 03:20

TỪ KHÓA LIÊN QUAN

w