Bài giảng Phát triển phần mềm phân tán - Bài 10: Exception handling - Vũ Thị Hương Giang

LESSON X. Exception  
Handling  
Vu Thi Huong Giang  
Objectives  
• After this lesson, students (learners) can:  
– Learn what an exception is, what have to do to handle  
exception  
– Distinguish the checked and unchecked exceptions  
– Implement the try-catch-finally blocks for catching and  
handling exceptions  
– Write methods that propagate exceptions.  
– Write programmer-defined exception classes.  
Content  
I. Exception & Exception handling  
II. Exception classes hierarchy  
III. try/catch/finally blocks  
IV. Throwing exceptions  
V. Print a stack trace message  
VI. Making custom exceptions  
I. Exception and Exception  
Handling  
1. Exception  
2. Exception Handling  
1. Exception-What are errors?  
• There are three categories or types of errors:  
– (1) Syntax errors  
– (2) Logic errors (sometimes called: semantic errors)  
– (3) Runtime errors  
• Syntax errors arise because the rules of the  
language have not been followed. They are  
detected by the compiler.  
• Logic errors occur when a program doesn't  
perform the way it was intended to.  
• Runtime errors occur while the program is  
running if the environment detects an operation  
that is impossible to carry out  
1. Exception-Error examples  
• User Input Errors:  
– connect to a URL which is incorrect  
– network exception  
• Device Errors:  
– printer is off/ out of paper  
– Network is down  
• Physical limitations:  
– Disks run out of memory,  
– quotas fill up  
– an infinite recursion causes a stack overflow.  
• Code errors:  
– divide by zero,  
– array out of bound,  
– integer overflow,  
– access a null pointer  
1. Exception-Definitions  
• Exception: an occurrence of an undesirable  
situation that can be detected during program  
execution. Examples:  
– Division by zero  
– Trying to open an input file that does not exist  
– An array index that goes out of bounds  
• When an exception occurs, or is thrown, the  
normal sequence of flow is terminated. The  
exception-handling routine is then executed; we  
say the thrown exception is caught  
1. Exception-Process when exception  
occurs  
1. When an exception occurs, Java allows a  
method to terminate abnormally  
2. It throws an object that encapsulates error  
information  
3. It does not return a value  
4. It exits immediately  
5. Execution does not resume at the point of  
method call  
6. JVM searches for an exception handler  
7. If none is found, the program crashes.  
I. Exception and Exception  
Handling  
1. Exception  
2. Exception Handling  
2. Exception Handling  
• Exception handling is generally used to handle  
abnormal events in a program.  
• When a method encounters a problem that  
disrupts the normal flow, it can cause the  
program to CRASH ! But with exception handling,  
the method can throw an exception which  
informs the caller that a problem occurred  
allowing the caller to perform alternative actions.  
• Exception handling enables more robust  
programming by providing ways of recovering  
from errors or problems  
2. Exception Handling (within a  
Program)  
• Can use an if statement to handle an exception  
Perform a task  
If the preceding task did not execute correctly  
Perform error processing  
Perform next task  
If the preceding task did not execute correctly  
Perform error processing  
2. Exception Handling  
• Exception handling streamlines error handling by  
allowing your program to define a block of code,  
called an exception handler that is executed  
automatically when an error occurs  
• All exception handling has the same goals:  
– 1. Anticipate the error by the user/system  
– 2. Return the program to a safe state that enables the  
user to execute other commands  
– 3. Inform the user of the error's cause  
– 4. Allow the user to save work and terminate the  
program gracefully.  
2. Exception Handling-Java's  
Mechanism of Exception Handling  
• When an exception occurs, an object of a  
particular exception classis created  
• Java provides a number of exception classes to  
effectively handle certain common exceptions,  
such as:  
– Division by zero: handled by the ArithmeticException  
class.  
– Invalid input: handled by the InputMismatchException  
class.  
– File not found: handled by the FileNotFoundException  
class.  
2. Exception Handling-Techniques  
• Techniques in Exception handling:  
– Terminate program  
– Fix error and continue  
– Log error and continue  
Example:  
code without exception handling  
import javax.swing.JOptionPane;  
public class Sample {  
public static void main(String[] args) {  
// TODO Auto-generated method stub  
System.out.println("Begin ...");  
String inputStr;  
int age;  
inputStr = JOptionPane.showInputDialog(null, "Age:");  
age = Integer.parseInt(inputStr);  
System.out.println("Your age: " + age);  
System.out.println("End ...");  
}
}
Example:  
code without exception handling  
• What would happen if the  
user enters an integer such  
as 10?  
• What would happen if the  
user enters a text “ten”  
instead of the number 10?  
Content  
I. Exception & Exception handling  
II. Exception classes hierarchy  
III. try/catch/finally blocks  
IV. Throwing exceptions  
V. Print a stack trace message  
VI. Making custom exceptions  
II. Exception class hierarchy  
Throwable  
Exception  
Error  
RuntimeException IOException AWTError  
NullPointerException  
ThreadDeath  
OutofMemoryError  
InputMismatchException  
ClassCastException  
ArrayIndexOutOfBoundException  
ArithmethicException  
Constructors and methods of class  
Throwable  
public Throwable()  
//Default constructor  
//Creates an instance of Throwable with an empty message string  
public Throwable (String strMessage)  
//Constructor with parameters  
//Creates an instance of Throwable with message string  
//specified by the parameter strMessage  
public String getMessage( )  
//Returns the detailed message stored in the object  
public void printStackTrace( )  
//Method to print the stack trace showing the sequence of  
//method calls when an exception occurs  
public void printStackTrace (PrintWriter stream)  
//Method to print the stack trace showing the sequence of  
//method calls when an exception occurs. Output is sent  
//to the stream specified by the parameter stream.  
public String toString( )  
//Returns a string representation of the Throwable object  
class Exception and its Constructors  
public Exception( )  
//Default constructor  
//Creates a new instance of the class Exception  
public Exception (String str)  
//Constructor with parameters  
//Creates a new instance of the class Exception.  
//The parameter str specifies the message string.  
Tải về để xem bản đầy đủ
pdf 60 trang Thùy Anh 22100 Free
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Phát triển phần mềm phân tán - Bài 10: Exception handling - Vũ Thị Hương Giang", để tải tài liệu gốc về máy hãy click vào nút Download ở trên

File đính kèm:

  • pdfbai_giang_phat_trien_phan_mem_phan_tan_bai_10_exception_hand.pdf