OOP Chapter IV
OOP Chapter IV
School of Informatics
Department of Computer Science
Exceptions Overview
Catching Exceptions
Exception Methods
Declaring Exceptions
Hardware failures
When an exception is dealt with, we say the exception was handled or caught
Unchecked Exceptions: is an exception that occurs at the time of execution. These are also called as
Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an
API. Runtime exceptions are numerous and ignored at the time of compilation.
Checked Exceptions: an exception that occurs at the compile time, these are also called as compile
time exceptions. These exceptions cannot simply be ignored at the time of compilation, the
programmer should take care of (handle) these exceptions.
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
public class JavaExceptionExample{
public static void main(String args[]){
14
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
Programs that obtain certain resources must return them to the system to
avoid so-called resource leaks.
In programming languages such as C and C++, the most common resource
leak is a memory leak.
Java performs automatic garbage collection of memory no longer used
by programs, thus avoiding most memory leaks.
However, other types of resource leaks can occur.
For example, files, database connections and network connections that are
not closed properly after they’re no longer needed might not be available for
use in other programs.
Finally block
17