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

11 Exception Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

11 Exception Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

5/10/21

@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 2

Outline
1. Exceptions
OBJECT-ORIENTED PROGRAMMING
2. Catching and handling exceptions
11. EXCEPTION AND EXCEPTION HANDLER
3. Exception delegation
Nguyen Thi Thu Trang
trangntt@soict.hust.edu.vn 4. User-defined exceptions

1 2

3 4

1.1. What is exception? 1.1. What is exception? (2)


• Exception = Exceptional event • Exception is a particular error
• Definition: An exception is an event that occurs in • Unexpected results
the execution of a program and it breaks the
expected flow of the program. • When an exception occurs, if it is not handled, the
program will exit immediately and the control is
returned to the OS
ERROR !!
Example:

3 4

1
5/10/21

5 6

1.2. Classical Error Handler Example


int devide(int num, int denom, int *error)
• Writing handling codes where errors occur
{
• Making programs more complex
if (denom != 0){
• Not always have enough information to handle *error = 0;
• Some errors are not necessary to handle return num/denom;
• Sending status to upper levels } else {
*error = 1;
• Via arguments, return values or global variables
return 0;
(flag)
}
• Easy to mis-understand
}
• Still hard to understand

5 6

7 8

Disadvantages Outline
• Difficult to control all cases 1. Exceptions
• Arithmetic errors, memory errors,…
2. Catching and handling exceptions
• Developers often forget to handle
3. Exception delegation
errors
• Human 4. User-defined exceptions
• Lack of experience, deliberately ignore

7 8

2
5/10/21

9 10

2.1. Goals of exception handling Separating code


l Classic programming: readFile() function: not separate
• Making programs more reliable, avoiding un- the main logic processing and error handling.
errorCodeType readFile() {
expected termination initialize errorCode = 0;
• Separating blocks of code that might cause exceptions open the file;
and blocks of code that handle exceptions
if (theFileIsOpen) {
………… determine the length of the file;
IF B IS ZERO GO TO ERROR
if (gotTheFileLength) {
C = A/B
PRINT C allocate that much memory;
GO TO EXIT if (gotEnoughMemory) {
read the file into memory;
ERROR: if (readFailed) {
DISPLAY “DIVISION BY ZERO” Error handling block
errorCode = -1;
}
EXIT: } else {
END errorCode = -2;
}

9 10

11 12

Classic Programming Exception Handling


l Exception mechanism allows focusing on writing code for the
} else { main thread and then handling exception in another place
errorCode = -3; readFile() {
} try {
open the file;
close the file; determine its size;
if (theFileDidntClose && errorCode == 0) { allocate that much memory;
errorCode = -4; read the file into memory;
close the file;
} else { } catch (fileOpenFailed) {
errorCode = errorCode and -4; doSomething;
} catch (sizeDeterminationFailed) {
} doSomething;
} else { } catch (memoryAllocationFailed) {
errorCode = -5; doSomething;
} catch (readFailed) {
} doSomething;
return errorCode; } catch (fileCloseFailed) {
} doSomething;
}
}

11 12

3
5/10/21

13 14

2.2. Models for handling exceptions 2.2. Models for handling exceptions (2)
• Object oriented approach • Exceptions need to be handled at the method that
• Packing unexpected conditions in an object causes the exceptions or delegated to its caller
• When an exception occurs, the object corresponding to the method
exception is created and stores all the detailed information
about the exception
• Providing an efficient mechanism in handling errors
• Separating irregular control threads with regular threads

13 14

15 16

2.3. Exception handling in Java 2.3. Exception handling in Java (2)


• Java has a strong mechanism
for handling exceptions • Key words
• Exception handling in Java is • try
done via object-oriented • catch
model:
• All the exceptions are • finally
representations of a class
derived from the class Throwable • throw
or its child classes
• throws
• These objects must send the
information of exceptions (type
and status of the program) from
the exceptions place to where
they are controlled/handled

15 16

4
5/10/21

17 18

2.3.1. try/catch block Example of not handling exceptions


• try ... catch block: Separating the regular block of program class NoException {
and the block for handling exceptions public static void main(String args[]) {
• try {…}: Block of code that might cause exceptions String text = args[0];
• catch() {…}: Catching and handling exceptions System.out.println(text);
try { }
// Code block that might cause exception }
}
catch (ExceptionType e) {
// Handling exception
}
q ExceptionType is a descendant of the Throwable

17 18

19 20

Example of handling exceptions Example of division by 0


public class ChiaCho0Demo {
public static void main(String args[]){
class ArgExceptionDemo {
try {
public static void main(String args[]) {
int num = calculate(9,0);
try {
System.out.println(num);
String text = args[0];
}
System.out.println(text);
catch(Exception e) {
}
System.err.println(”Co loi xay ra: " + e.toString());
catch(Exception e) {
}
System.out.println(“Hay nhap tham so khi chay!");
}
}
static int calculate(int no, int no1){
}
int num = no / no1;
}
return num;
}
}

19 20

5
5/10/21

21 22

2.3.2. Exception hierarchical tree in Java 2.3.2. Exception hierarchical tree in Java
Error indicates very
Throwable is a base serious bugs, the
class (ancestor) for all program can not Exception is a basic
exceptions controlled these bugs. class for all the
Object Object
Ex: VirtualMachineError controllable errors.
OutOfMemoryError Ex: ArithmeticException,
Throwable Throwable BufferOverflowException

Error Exception Error Exception

... RuntimeException ... RuntimeException


... ...

... ...

21 22

23 24

public class StckExceptionDemo {


a. Class Throwable public static void main(String args[]){
try {
int num = calculate(9,0);
• A variable of type String to store detailed information System.out.println(num);
about exceptions that already occurred }
catch(Exception e) {
• Some basic functions
System.err.println(“Co loi xay ra :"
• new Throwable(String s): Creates an exception + e.getMessage());
and the exception information is s e.printStackTrace();
• String getMessage(): Get exception information }
}
• String getString(): Brief description of exceptions static int calculate(int no, int no1) {
• void printStackTrace(): Print out all the involving int num = no / no1;
information of exceptions (name, type, location...) return num;
•… }
}

23 24

6
5/10/21

25 26

b. Class Error c. Class Exception


• Contains critical and unchecked exceptions (unchecked
exception) because it might occur at many parts of the • Has exception types that should/must
program. be caught and handled or delegated.
• Is called un-recoverable exception • Developers might create their own
• Do not need to check in your Java source code exceptions by inheriting from Exception
• Child classes: • RuntimeException might appear while
• VirtualMachineError: InternalError, OutOfMemoryError, JVM is running
StackOverflowError, UnknownError • Not mandatory to catch exceptions even
• ThreadDeath there might be errors
• LinkageError: • Should not write your own exception
• IncompatibleClassChangeError inheriting from this class
• AbstractMethodError, InstantiationError, NoSuchFieldError,
NoSuchMethodError…
• …
• …

25 26

27 28

Some derived classes of Exception Example of IOException


import java.io.InputStreamReader;
• ClassNotFoundException, SQLException import java.io.IOException;
• java.io.IOException: public class HelloWorld{
public static void main(String[] args) {
• FileNotFoundException, EOFException…
InputStreamReader isr = new
• RuntimeException: InputStreamReader(System.in);
• NullPointerException, BufferOverflowException try {
• ClassCastException, ArithmeticException System.out.print("Nhap vao 1 ky tu: ");
• IndexOutOfBoundsException: char c = (char) isr.read();
System.out.println("Ky tu vua nhap: " + c);
• ArrayIndexOutOfBoundsException,
}catch(IOException ioe) {
• StringIndexOutOfBoundsException…
ioe.printStackTrace();
• IllegalArgumentException:
}
• NumberFormatException, InvalidParameterException…
}
•… }
27 28

7
5/10/21

29 30

2.3.3. Nested try – catch blocks 2.3.4. Multiple catch block


• A small part of a code block causes an error, but the n A block of code might cause more than one exception
whole block cause another error à Need to have nested à Need to use multiple catch block.
exception handlers. try {
• When there are nested try blocks, the inner try block will // May cause multiple exception
be done first.
try { } catch (ExceptionType1 e1) {
// May cause IOException // Handle exception 1
try {
// May cause NumberFormatException
} catch (ExceptionType2 e2) {
} // Handle exception 2
catch (NumberFormatException e1) { } ...
// Handle NumberFormatException
} n ExceptionType1 must be a derived class or an
} catch (IOException e2) { level-equivalent class of the class ExceptionType2
// Handle IOException
}
(in the inheritance hierarchy tree)

29 30

31 32
n ExceptionType1 must be a derived class or an level-equivalent
n ExceptionType1 must be a derived class or an level- class of the class ExceptionType2 (in the inheritance hierarchy
equivalent class of the class ExceptionType2 (in the
inheritance hierarchy tree) tree)
class MultipleCatch1 { class MultipleCatch1 {
public static void main(String args[]) public static void main(String args[])
{ {
try { try {
String num = args[0]; String num = args[0];
int numValue = Integer.parseInt(num); int numValue = Integer.parseInt(num);
System.out.println("Dien tich hv la: " System.out.println("Dien tich hv la: "
+ numValue * numValue); + numValue * numValue);
} catch(Exception e1) { } catch(ArrayIndexOutOfBoundsException e1) {
System.out.println("Hay nhap canh cua System.out.println(“Hay nhap canh cua hv!");
hv!"); } catch(NumberFormatException e2){
} catch(NumberFormatException e2){ System.out.println(“Hay nhap 1 so!");
System.out.println("Not a number!"); }
} }
} Error D:\exception java.lang.NumberFormatException }
} has already been caught
31 32

8
5/10/21

class MultiCatch2 { 33 34
public static void main( String args[]) { ...
try { public void openFile(){
// format a number try {
// constructor may throw FileNotFoundException
// read a file FileReader reader = new FileReader("someFile");
// something else... int i=0;
} while(i != -1) {
catch(IOException e) { //reader.read() may throw IOException
i = reader.read();
System.out.println("I/O error "+e.getMessage(); System.out.println((char) i );
} }
catch(NumberFormatException e) { reader.close();
System.out.println("--- File End ---");
System.out.println("Bad data "+e.getMessage();
} catch (FileNotFoundException e) {
} //do something clever with the exception
catch(Throwable e) { // catch all } catch (IOException e) {
System.out.println("error: " + e.getMessage();} //do something clever with the exception
}
}
}
} ...
}
33 34

35 36

2.3.5. finally block The syntax try ... catch ... finally
try {
• Ensure that every necessary tasks are done when an
// May cause exceptions
exception occurs
}
• Closing file, closing socket, connection
• Releasing resource (if neccessary)...
catch(ExceptionType e) {
// Handle exceptions
• Must be done even there is an exception occurring or not. }
finally {
No exception /* Necessary tasks for all cases:
finally exception is raised or not */
}
try block q If there is a block try, there must be a block catch or a
block finally or both
catch block finally
Exception

35 36

9
5/10/21

37 38

class StrExceptionDemo { public void openFile(){


static String str; try {
public static void main(String s[]) { // constructor may throw FileNotFoundException
try { FileReader reader = new FileReader("someFile");
System.out.println(“Before exception”); int i=0;
staticLengthmethod(); while(i != -1) {
System.out.println(“After exception”); //reader.read() may throw IOException
} i = reader.read();
catch(NullPointerException ne) { System.out.println((char) i );
System.out.println(“There is an error”); }
} } catch (FileNotFoundException e) {
finally { //do something clever with the exception
System.out.println(“In finally”); } catch (IOException e) {
} //do something clever with the exception
} } finally {
reader.close();
static void staticLengthmethod() { System.out.println("--- File End ---");
System.out.println(str.length()); }
} }
}

37 38

39 40

Outline Two ways to deal with exceptions


• Handle immediately
1. Exceptions • Using the block try ... catch (finally if neccessary).

2. Catching and handling exceptions • Delegating to its caller:


n If we don’t want to
3. Exception delegation handle immediately
n Using throw and throws
4. User-defined exceptions

39 40

10
5/10/21

41 42

3.1. Exception delegation 3.1. Exception delegation (2)


• A method can delegate exceptions to its caller:
• If a method has some code that throws an exception, its
• Using throws at the method definition to tell its declaration must declare a “throw” of that exception or the
caller of ExceptionType that it might cause an parent class of that exception
exception ExceptionType public void myMethod(int param) {
• Using throw anExceptionObject in the body of
if (param < 10) {
function in order to throw an exception when throw new Exception("Too low!");
necessary }
• For example //Blah, Blah, Blah...
public void myMethod(int param) throws Exception{ }
if (param < 10) {
à unreported exception java.lang.Exception; must be
throw new Exception("Too low!");
} caught or declared to be thrown
//Blah, Blah, Blah...
}

41 42

43 44

3.1. Exception delegation (3) 3.1. Exception delegation (3)


• A method without exception declaration will throw • At the caller of the method that has
RuntimeException because this exception is
delegated to JVM exception delegation (except
• Example RuntimeException):
class Test {
• Or the caller method must delegate to its caller
public void myMethod(int param) {
if (param < 10) { • Or the caller method must catch the delegated
throw new RuntimeException("Too low!"); exception (or its parent class) and handle
} immediately by try... catch (finally if
//Blah, Blah, Blah... necessary)
}
}

43 44

11
5/10/21

45 46
public class DelegateExceptionDemo {
public class DelegateExceptionDemo { public static void main(String args[]){
public static void main(String args[]){ int num = calculate(9,3);
int num = calculate(9,3); System.out.println(“Lan 1: ” + num);
System.out.println(“Lan 1: ” + num); num = calculate(9,0);
System.out.println(“Lan 2: ” + num);
num = calculate(9,0); }
System.out.println(“Lan 2: ” + num); static int calculate(int no, int no1)
} throws Exception {
static int calculate(int no, int no1) if (no1 == 0)
throws ArithmeticException { throw new
ArithmeticException(”Cannot divide by 0!");
if (no1 == 0) int num = no / no1;

Compile
throw new return num;
ArithmeticException(”Cannot devide by 0!"); }
int num = no / no1; }
G:\Java Example\DelegateExceptionDemo.java:3: unreported exception java.lang.Exception;
must be caught or declared to be thrown
return num; int num = calculate(9,3);
} ^
G:\Java Example\DelegateExceptionDemo.java:5: unreported exception java.lang.Exception;
} must be caught or declared to be thrown
num = calculate(9,0);

45 46

47 48

public class DelegateExceptionDemo {


public static void main(String args[]){
try {
3.1. Exception delegation (4)
int num = calculate(9,3);
System.out.println(“Lan 1: ” + num);
num = calculate(9,0);
System.out.println(“Lan 2: ” + num); • A method can delegate more than 1 exception
} catch(Exception e) { public void myMethod(int age, String name)
System.out.println(e.getMessage()); throws ArithmeticException, NullPointerException{
} if (age < 18) {
} throw new ArithmeticException
static int calculate(int no, int no1) (“Age must be at least 18”);
throws Exception { }
if (no1 == 0) if (name == null) {
throw new throw new NullPointerException
ArithmeticException(”Cannot devide by 0!"); (“Name must be provided”);
int num = no / no1; }
return num; //Blah, Blah, Blah...
} }
}

47 48

12
5/10/21

49 50

3.2. Exception propagation 3.2. Exception Propagation (2)


C()
C() throws exception
• Scenario:
B() B()
• Assuming that in main() method A() is called, A() A()
B() is called in A(), C() is called in B(). Then a main()
main()
stack of method is created.
If C() has an error and throws an exception but in C() that
• Assuming that in C() there is an exception
exception is not handled, hence there is only one place that
occurring. handles the exception, that place is where C() is called, it is the
method B().

If in B() there is no exception handling, then the exception must


be handled in A() … This is called Exception Propagation
If in main(), the exception thrown from C() can not be handled,
the program will be interrupted.

49 50

51 52

3.3. Inheritance and exception delegation 3.3. Inheritance and exception delegation(2)
class Disk {
• Whenoverriding a method of a parent class, void readFile() throws EOFException {}
methods in its child classes can not throw any }
new exception class FloppyDisk extends Disk {
void readFile() throws IOException {} // ERROR!
}
à Overriden method in a child class can only
throw a set of exceptions that are/similar to/ a class Disk {
subset of exceptions thrown from the parent void readFile() throws IOException {}
class. }
class FloppyDisk extends Disk {
void readFile() throws EOFException {} //OK
}

51 52

13
5/10/21

53 54

3.4. Advantages of exception delegation Outline


• Easy to use 1. Exceptions
• Making programs easier to read and more reliable
• Easy to send control to the places that can handle 2. Catching and handling exceptions
exceptions
• Can throw many types of exceptions 3. Exception delegation
Separating exception handling from the main code

4. User-defined exceptions
• Do not miss any exception (throw automatically)
• Grouping and categorizing exceptions
• Making program easier to read and more reliable

53

53 54

55 56

4. User-defined exception Using self-defined exceptions


Declaring that an exception might be thrown
• Exceptions provided can not controll all the errors à Need
to have exceptions that are defined by users. public class FileExample
{
• Inheriting from the class Exception or one of its child public void copyFile(String fName1,String fName2)
classes throws MyException
• Having all the methods of the class Throwable {
if (fName1.equals(fName2))
public class MyException extends Exception {
throw new MyException("File trung ten");
public MyException(String msg) { // Copy file
super(msg); System.out.println("Copy completed");
} }
public MyException(String msg, Throwable cause){ }
super(msg, cause);
}
Throwing an exception
}

55 56

14
5/10/21

57 58

Modify the following source code so that copyFile()


Using self-defined exceptions
method will throw 2 exceptions:
• Catching and handling exceptions Quiz • MyException if the 2 file names are equal, and
public class Test { • IOException if there is any error during the copy file process
public static void main(String[] args) { public class FileExample {
FileExample obj = new FileExample(); public void copyFile(String fName1,String fName2)
try { throws MyException{
String a = args[0]; if (fName1.equals(fName2))
String b = args[1]; throw new MyException(”Duplicate file name");
obj.copyFile(a,b);
} catch (MyException e1) { // Copy file
System.out.println(e1.getMessage());
}
System.out.println("Copy completed");
catch(Exception e2) {
}
System.out.println(e2.toString());
}
}
}
}

57 58

15

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy