exception
exception
Yeabsira
Exception
Exception
Handling
Yeabsira
19-Nov-2024
inheritance
Yeabsira
Exception
Exception
Handling
Exception
Exception Handling
inheritance
Exception (Introduction)
Yeabsira
Exception
Exception
Exception
Exception message format Handling
Exception
try{ Exception
Handling
// exception causing code
}
catch(Exception-Type ex){
// what to do when the exception is thrown
}
Example
try{
int a=4/0;
}
catch(ArithmeticException ex){
System.out.println(”You can not divide by Zero”);
}
inheritance
checked and unchecked exceptions
Yeabsira
Exception
Unchecked Exception checked Exception
Exception
Usually occur because of pro- Usually occur because of er- Handling
▶ NullPointerException ▶ IOException
▶ ▶ FileNotFoundException,
IllegalArgumentException ▶ SocketException
▶ IllegalStateException
inheritance
checked exceptions handling
Yeabsira
try-catch Exception
Exception
void readFile(){ Handling
try{
FileReader reader = new FileReader (”file.txt”);
// read from file . . .
} catch (FileNotFoundException e){
throws e; }
}
- OR -
Duck the exception
void readFile() throws FileNotFoundException {
// other methods calling on this method should
implement the try catch not this one
FileReader reader = new FileReader(”file.txt”);
// read from file . . .
}
inheritance
multiple exceptions
Yeabsira
Exception
Exception
Handling
try with multiple catch
void readFile(){
try{
FileReader reader = new FileReader (”file.txt”);
// read from file . . .
} catch (FileNotFoundException ex1){
throws ex1;
}
catch (IOException ex2){
throws ex2;
}
}
inheritance
Finally Block
Yeabsira
Exception
▶ The finally block will execute whether or not an Handling
exception is thrown
▶ The finally block will execute even if a try block exits by
using a return, break or continue statement
void readFile(){
try{
FileReader reader = new FileReader (”file.txt”);
// read from file . . .
} catch (FileNotFoundException ex1){
System.out.println(”There was an exception”);
}
finaly {
System.out.println(”This will almost always be
executed”); }
}
inheritance
Exception hierarchy
Yeabsira
Exception
Exception
Handling