Exception in Java
Exception in Java
Exception in Java
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run
time that disrupts or stops the normal flow of the program. When an exception occurs program execution gets
terminated.
There can be various reasons that can cause a program to throw exception. For example: Opening a non-existing
file in your program, Network connection problem, invalid input data provided by user or accessing the table in
database which is not created.
Exception Handling
Exception handling ensures that the flow of the program doesn’t break when an exception occurs. By handling
we make sure that all the statements execute and the flow of program doesn’t break. One of the important
purposes of exception handling in Java is to continue program execution after an exception is caught and
handled. The execution of a Java program does not terminate when an exception occurs. Once the exception is
resolved, program execution continues till completion.
Java Exception classes: The java.lang.Throwable class is the root class of Java Exception hierarchy which is
inherited by two subclasses: Exception and Error.
Difference between error and exception
Errors indicate that something very severe occured .The error can not be recovered by the programmer.
Exceptions are events that occur in the code. A programmer can handle such conditions and take necessary
corrective actions.
1) Checked Exception All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, you will get compilation error. For example,
SQLException, IOException, ClassNotFoundException etc.
2) Unchecked Exception Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are
not checked at compile-time so compiler does not check whether the programmer has handled them or not but
it’s the responsibility of the programmer to handle these exceptions and provide a safe exit.For
example:ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsExc eption etc.
class E {
}}
Here arithmeticException will be occured and the program will be terminated and the compiler will inform
about this exception on command prompt.
Is it possible to have multiple try blocks with only one catch block in java?
We cannot have multiple try blocks with a single catch block. Each try block must be followed by
catch or finally. Still if you try to have a single catch block for multiple try blocks a compile time
error is generated.
Explanation
The exception is neither handled in the catch block with respect to try3, try2 or try1 because of type
mismatch. Also, it does not get handled by the main catch block with Arithmetic Exception. Finally, it
is caught by the main catch block of ArrayIndexOutOfBoundsException (e4).
Although Java’s built-in exceptions handle most common errors, you will probably want to create
your own exception types to handle situations specific to your applications. This is quite easy to do:
just define a subclass of Exception (which is, of course, a subclass of Throwable).
import java.util.ArrayList;
import java.util.Arrays;
// create an exception class
class CustomException extends Exception {
public CustomException(String message) {
// call the constructor of Exception class
super(message);
}
}
class Main {
ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript"));
// check the exception condition
public void checkLanguage(String language) throws CustomException {
// throw exception if language already present in ArrayList
if(languages.contains(language)) {
throw new CustomException(language + " already exists");
}
else {
// insert language to ArrayList
languages.add(language);
System.out.println(language + " is added to the ArrayList");
}
}
public static void main(String[] args) {
// create object of Main class
Main obj = new Main();
// exception is handled using try...catch
try {
obj.checkLanguage("Swift");
obj.checkLanguage("Java");
}
catch(CustomException e) {
System.out.println("[" + e + "] Exception Occured");
}
}
}
Explanation
We have created a class for custom exceptions called CustomException, which inherits Exception
class (this is mandatory). The constructor of this class has a parameterized constructor, which calls the
superclass constructor.
Inside the method checkLanguage(), we have checked the exception condition, and if the exception
occurs, the try..catch block handles the exception.