Introduction An exception is an event that occurs during the execution of a program, that disrupts the normal flow of instructions. The Java programming language uses exceptions to handle errors and other exceptional events. In this post, we will learn about exceptions and how to handle them. In Java, Throwable class is the root hierarchy for all exceptions.
Types of exceptions According to Oracle, there are 3 types of exceptions. They are as follows:
Checked Exception: Exceptions which are checked by compiler so that the program runs smoothly are called checked exception. For example: Program for writing something in a file. Even though the file to be written to is present, the compiler would throw an exception at compile time giving message unreported exception: file not found. To handle this we must catch the exception. That we would see in subsequent sections.
Unchecked Exception: Exceptions which can't be checked by compiler but caught during run-time only, are called unchecked exception. For example: calculating an arithmetic expression that results in something which is not a valid output.
Error: Errors are something which are not traceable and can't be resolved/recovered by our code. This is issue with the system and not the program. For example, the system goes out of memory while executing the program is an Error.
Java Throw keyword The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception.
throw new IOException("device error");
Java Throws keyword
The Java throws keyword is used to declare an exception. It indicates what exception type may be thrown by a method, so that the programmer can provide the exception handling code so that normal flow can be maintained.
There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
NOTE: Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as NullPointerException, it is programmers duty to handle that within code.
NOTE: If you are calling a method that declares an exception, it must either be caught or declared with exception in the handler class.
1. Catching the exception using try/catch
import java.io.*;
class test{
void method()throws IOException{
throw new IOException("device error");
}
}
public class testaccess{
public static void main(String args[]){
try{
test m=new test();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow");
}
}
2. Declaring the exception
import java.io.*;
class test{
void method()throws IOException{
throw new IOException("device error");
}
}
class testaccess{
public static void main(String args[])throws IOException{
test m=new test();
m.method();
System.out.println("normal flow...");
}
}
Throw v/s Throws
Throw is used to throw an exception for a method, whereas, throws defines what kind of exception would be thrown by a method.
Throw can't handle multiple exception, throws can declare multiple exceptions.
Throw is used inside the method, whereas, throws is used in the method signature.
What is exception propagation? Exception propagation is the phenomenon that states that how an exception occurring at the top level, travels to the caller method until it is caught. In the below example, the exception occurs in the method(), but it isn't caught until it reaches the test2().
import java.io.*;
class test{
void method()throws IOException{
throw new IOException("device error");
}
void test1()throws IOException{
method();
}
void test2() throws IOException{
test1();
}
}
public class testaccess{
public static void main(String args[]){
try{
test m=new test();
m.test2();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow");
}
}
Java Finally block The finally statement lets you execute a segment of code, after try-catch block, regardless of the result. Final v/s Finally v/s Finalize
Final - Final is an access modifier in JAVA. Final keyword is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed once initialized.
Finally - Finally refers to a block segment and is used to place important code, it will be executed whether exception is handled or not.
Finalize - Finalize method is used to perform clean up processing just before object is garbage collected.
Java custom exception In Java we can create our own customized exception to provide more user-friendly message or for handling the exception as per our needs. Below in an example.
class InvalidAge extends Exception{
private static final long serialVersionUID = 1L;
InvalidAgeException(String s){
super(s);
}
}
class CustomExceptionHandling{
static void validate(int age)throws InvalidAge{
if(age<18)
throw new InvalidAge("not a valid age");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(15);
}catch(Exception e){
System.out.println(e);
}
}
}
Summary In this post, we have learnt about the Java Errors and Exceptions. How to handle them. We have also seen how the try/catch/finally blocks work.
Comments