10. Exception Handling

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

10.

Exception Handling
1. Exceptions
Exception

Event that occurs in the execution of a prog and breaks the expected flow of
the prog if it is not handled.

Writing handling codes where errors occur:

Making prog more complex


Not always have enough info to handle
Some errors are not necessary to handle

Sending status to upper levels

Via arguments, return vals or global vars (flag)


Easy to mis-understand
Still hard to understand

Disadvantages

Difficult to control all cases


Dev often forget to handle errors

2. Catching and handling exceptions


Goals of exception handling

Make prog more reliable, avoid unexpected termination.


Seperate blocks of code that might cause exceptions and blocks of code
that handle exceptions.

Exception mechanism allows focusing on writing code for the main thread
and then handling exception in another place
readFile(){
try{
//open the file
//determine its size
//allocate that much mem
// read the file into mem
//close the file
} catch(fileOpenFailed){
// do smth
} catch(sizeDeterminationFailed){
// do smth
} catch(memoryAllocationFailed){
// do smnth
} catch(readFailed){
//do smth
} catch(fileCloseFailed){
//do smth
}
}

2.1 Models for handling exceptions

OO approach

pack unexpected conditions in an obj


when an exception occurs, the obj corresponding to the 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.

Exceptions need to be handled at the method that causes the exceptions or


delegated to its caller method.
2.2 Exception handling in Java
Exception handling in Java followed OO approach

All the exceptions are representations of a class derived from the class
Throwable (or its child classes).
These objs must send the info of exceptions (type and prog status) from the
place that exception occured to where they are controlled/handled.

Try/catch block

try{
//code block that might cause exception
} catch(ExceptionType e){ // descendant of Throwable
// handling exception
}

Exception hierarchical tree in Java


Class Error:
Contains critical and unchecked exceptions because it might occur at
many parts of the prog
Called un-recoverable exception
Do not need to check in java source code
Class Exception:
Has exception types that should or must be caught and handled or
delegated.
Dev can create their own exceptions by inheriting form Exception

IOException

import java.io.InputStreamReader;
import java.io.IOException;

public class HelloWorld{


public static void main(String[] args) {
InputStreamReader isr = new
InputStreamReader(System.in);
try {
System.out.print("Nhap vao 1 ky tu: ");
char c = (char) isr.read();
System.out.println("Ky tu vua nhap: " + c);
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}

Nested try/catch

try{
// may cause exception type 1
try{
// may cause exception type 2
} catch(ExceptionType2){
// handle exception type 2
}
} catch(ExceptionType1){
// handle exception type 1
}

Multiple catch block

try{
// may cause multiple exception
} catch(ExceptionType1 e1){
//handle exc type 1
} catch(ExceptionType2 e2){
//handle exc type 2
}

Warning

ExceptionType1 must be a derived class or an level-equivalent class of the


ExceptionType2 class. (In the inheritance hierarchy tree)

Example
public static void main( String args[]) {
try {
// format a number
// read a file
// something else...
} catch(IOException e) {
System.out.println("I/O error "+e.getMessage();
} catch(NumberFormatException e) {
System.out.println("Bad data "+e.getMessage();
} catch(Throwable e) { // catch all
System.out.println("error: " + e.getMessage();
}
}

finally block

Ensure that every necessary tasks are done when an exception occurs
Closing file, closing socket, connection
Releasing resource (if necessary)
Must be done even there is an exception occurring or not

try{
// code block that can have exceptions
} catch(Exception e){
//handle exception
} finally{
// task for all cases, whether exceptions are raised or not
}

3. Exception delegation (sự uỷ thác)


There are two way to deal with exceptions:

Handle it immediately
Delegate to its caller if don't want to handle immediately, by using throw
and throws

A method can delegate exceptions to its caller:


Using throws at the method definition to tell its caller of ExceptionType
that is might cause an exception ExceptionType
Using throw AnExceptionObject in the body of function in order to throw
an exception when necessary.

public void myMethod(int param) throws Exception{


// must declare a throw of Exception or the parent class of that exception
if (param < 10){
throw new Exception("Too low!");
}
// other block of code
}

Warning

A method without exception declaration will throw RunTimeException because


this exception is delegated to JVM.

At the caller of the method that has exception delegation (Except


RunTimeException):
The caller method must delegate to its caller
Or the caller method must catch the delegated exception (or its parent
class) and handle it immediately (by try{}... catch , finally )

public class Demo{


public static void main(String args[]){
try{
int num = cal(9,3);
System.out.println("Lan 1" + num);
int num2 = cal(9,0);
System.out.println("Lan 2" + num2);
} catch(Exception e){
e.printStackTrace();
}
}
static int cal(int i1, int i2) throws Exception {
if(i2 == 0){
throw new ArithmeticException("Cannot divide by 0.");
}
int num = i1/i2;
return num;
}
}

Lan 13
java.lang.ArithmeticException: Cannot divide by 0.
at Demo.cal(Demo.java:16)
at Demo.main(Demo.java:8)

A method can delagate more than 1 exception

public void myMethod(int param1, int param2) throws ExceptionType1,


ExceptionType2{
if(param1 < 10){
// throw new ExceptionType1("...")
}
if(param2 > 10){
// throw new ExceptionType2("...")
}
}

Exception Propagation (Lan truyền)


Scenario: method A() called in main(), method B() called inside A(), method C()
called inside B(). An exception will be occur inside C()
If C() doesn't handle exception, B() will be demanded to handle it.
If there is no exception handling in B(), the exception must be handled in A().
If the exception thrown from C() can not be handled, the prog will be
interupted.

Inheritance and exception delegation

Note

When overriding a method of a parent class, methods in its child classes can
not throw any new exception but only a set of exceptions that are a subset
of exceptions thrown from the parent class (or similar to).

Advantage of exception delegation

Easy to use
Separate exception handling from the main code
Throw automatically, do not miss any exception
Group and categorize exceptions
Make prog easier to read and more reliable

4. User-defined exceptions
why do we need user-defined exceptions ?

To catch and provide specific treatment to a subset of existing Java


exceptions.
Business logic exceptions: These are the exceptions related to business
logic and workflow. It is useful for the application users or the
developers to understand the exact problem.

Must be inherited from Exception class or one of its child.


Have all the methods of the class Throwable

public class MyExc extends Exception{


public MyException(String msg){
super(msg);// not neccessary
}
public MyException(String msg, Throwable cause){
super(msg, cause);
}
}
// ---
public class FileExample
{
public void copyFile(String fName1,String fName2) throws MyException
{
if (fName1.equals(fName2)) {
throw new MyException("File trung ten");
}
// Copy file
System.out.println("Copy completed");
}
}
// ---
public class Test{
public static void main(String[] args) {
FileExample obj = new FileExample();
try {
String a = args[0];
String b = args[1];
obj.copyFile(a,b);
} catch(MyException e1) {
System.out.println(e1.getMessage());
}
catch(Exception e2) {
System.out.println(e2.toString());
}
}
}

You might also like