JAVA-Exceptions
Introduction to Java Exception handling
Java exception handling is a mechanism that use to handle runtime and compile-time errors. Exceptions are disrupting the normal flow of the program; Exception is an abnormal condition. So java introduced exception handling in order to maintain the normal flow of the program. Also, the exception is an object that is thrown at run time. ClassNotFound Exception, IOException, SQLException, and RemoteException are some runtime errors that are handling by exception handling.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;public class Exception {
public static void main(String args[]) throws FileNotFoundException {
File file = new File(“H://Test.txt”);
FileReader fr = new FileReader(file);
}
}
Output
Exception in thread “main” java.io.FileNotFoundException: H:\Test.txt (The system cannot find the file specified)
Types of Java Exceptions
Checked exceptions
Unchecked exceptions
Error
Difference between checked and unchecked exceptions
Exceptions that are checked at compile time are known as checked exceptions and exceptions that are checked at run-time are inherits to the unchecked exceptions.
SQLException and IOException are examples of the checked exceptions and Arithmetic, NullPointerException and ArrayIndexOutofBound are examples of unchecked exceptions.
Errors cannot recover; Ex: Out of memory, Assertion error, etc.
Keywords in Java Exception
try: Try block is where you should place your exception code. It must be followed by either catch or finally keywords. And we cannot use the try keyword alone.
catch: Catch block is used to handle the exception and this also cannot use alone; It can be followed by finally block later.
Syntax
try {
// try block
} catch (ExceptionName e) {
// Catch block
}
finally: This keyword executes the important part of a program and it must be executed whether the exception is handled or not.
Syntax
try {
//try block where you should place your exception
} catch {
// catch block where you handle the exception
}finally {
// finally block that you must execute whether you handle the exception or not.
}
throw/throws: “throw” keyword used to throw an exception and the “throws” keyword used to declare an exception; It always used with method signature.
sample program
public class CheckException{
static void checkAge(int age) {
if (age < 26) {
throw new.ArithmeticException("Access denied");
}
else {
System.out.println("Access granted");
}
}
public static void main(String[] args) {
checkAge(24);
}
}
Throws syntax
return_type method_name() throws exception_class_name{
//method code
}
sample program
import java.io*class CheckException{
void method()throws IOException{ throw new IOException("Error");
}
}public calss Test{
public static void main(String args[]){ try{ CheckException new = new CheckException();
new.method(); }catch(Exception e){
System.out.println("Exception handled successfully");
}
System.out.println("Normal...") }
}