Exception Handling
Exception Handling
What is Exception?
An exception (or exceptional event) is a problem/ error that arises during the
execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
1. Checked Exception
2. Unchecked Exception
3. Error
For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
importjava.io.File;
importjava.io.FileReader;
publicclassFilenotFound_Demo{
publicstaticvoid main(Stringargs[]){
Filefile=newFile("E://file.txt");
FileReaderfr=newFileReader(file);
}
}
If you try to compile the above program, you will get the following
exceptions.
Output:
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReaderfr = new FileReader(file);
^
1 error
Example
PublicclassUnchecked_Demo
{
publicstaticvoid main(Stringargs[])
{
intnum[]={1,2,3,4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get the following
exception.
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
atExceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
3) Error:These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer. Errors are typically ignored in your
code because you can rarely do anything about an error. For example, stack
overflow, OutOfMemoryError,etc. They are also ignored at the time of
compilation.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The
exception class is a subclass of the Throwable class. Other than the exception
class there is another subclass called Error which is derived from the
Throwable class.
statement 1;
statement 2;
statement 3;//exception occurs
statement 4;
statement 5;
statement 6;
Suppose there are 6 statements in our program and there occurs an exception
at statement 3, the rest of the code will not be executed i.e. statement 4 to 6
will not be executed. If we perform exception handling, the rest of the
statement will be executed. That is why we use exception handling in Java.
Java provides five keywords that are used to handle the exception. The
following table describes each.
Keyword Description
Syntax:
try
{
// code that may raise exception
}
catch (ExceptionName e1)
{
// Catch block
}
//rest code of the program
Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.
JavaExceptionExample.java
Catching Exceptions
A method catches an exception using a combination of the try and catch
keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and
the syntax for using try/catch looks like the following –
Syntax
Try
{
// Protected code
} catch (ExceptionName e1)
{
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an
exception occurs, that exception occurred is handled by catch block associated
with it. Every try block should be immediately followed either by a catch block
or finally block.
A catch statement involves declaring the type of exception you are trying to
catch. If an exception occurs in protected code, the catch block or blocks that
follows the try is checked. If the type of exception that occurred is listed in a
catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.
Example:
class Excep
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
}
The previous statements demonstrate three catch blocks, but you can have any
number of them after a single try. If an exception occurs in the protected code,
the exception is thrown to the first catch block in the list. If the data type of the
exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which case the
current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example 1:
Here is code segment showing how to use multiple try/catch statements.
// Demonstrate multiple catch statements.
import java.util.*;
class Multi_Exec {
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
try {
System.out.println("Enter Value");
int a = s.nextInt();
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Example 2:
// A Java program to demonstrate that we needed multiple catch blocks for
// multiple exceptions
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
System.out.println(“Enter a value ");
int n = scn.nextInt();
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}
Output 1:
Enter a value
Madhu
Exception encountered java.lang.NumberFormatException:
For input string: "Madhu"
Output 2:
Enter a value
0
Arithmetic Exception encountered java.lang.ArithmeticException: / by zero
throw Keyword:
The Java throw keyword is used to throw an exception explicitly.
Example
Output:
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
throws Keyword:
If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a
method's signature.
A throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions, except those of type Error or RuntimeException,
or any of their subclasses.
All other exceptions that a method can throw must be declared in the throws
clause. If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
Output:
Inside check function
caughtjava.lang.ArithmeticException: demo
Difference between throw and throws
throw throws
Finally Block:
The finally block follows a try block or a last catch block.
The finally block in java is used to put important codes such as clean up
code e.g. closing the file or closing the connection.
The finally block executes whether exception rise or not and whether
exception handled or not.
class GFG {
public static void main(String[] args)
{
try {
System.out.println("inside try block");
System.out.println("Arithmetic Exception");
}
// Always execute
finally {
System.out.println(
"finally : i execute always.");
}
}
}
Output
inside try block
17
finally : i execute always.
Case 2: When the exception rises and handled by the catch block
In this case, the program throws an exception but handled by the catch block,
and finally block executes after the catch block.
import java.io.*;
class GFG {
System.out.println(
"catch : exception handled.");
}
// Always execute
finally {
Case 3: When exception rise and not handled by the catch block
In this case, the program throws an exception but not handled by catch so
finally block execute after the try block and after the execution of finally block
program terminate abnormally, But finally block execute fine.
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println("Inside try block");
System.out.println(
"catch : exception not handled.");
}
// Always execute
finally {
System.out.println(
"finally : i will execute always.");
}
// This will not execute
System.out.println("i want to run");
}
}
Output
Inside try block
finally : i will execute always.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
Note the following −
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block is
present.
The try block cannot be present without either catch clause or finally
clause.
Any code cannot be present in between the try, catch, finally blocks.
User-defined/custom Exceptions:
Java provides us the facility to create our own exceptions which are basically
derived classes of Exception.
Creating our own Exception is known as a custom exception or user-defined
exception.
Basically, Java custom exceptions are used to customize the exception
according to user needs.
In simple words, we can say that a User-Defined Exception or custom
exception is creating your own exception class and throwing that exception
using the ‘throw’ keyword.
You just need to extend the predefined Exception class to create your own
Exception. These are considered to be checked exceptions.
Example:
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (MyException ex)
{
System.out.println("Caught the exception");
Output:
F:\java>java MyException
Method Description
hasNext() It returns true if the iterator has more elements
otherwise it returns false.
next() It returns the element and moves the cursor
pointer to the next element.
remove() It removes the last elements returned by the
iterator. It is less used.
There are many methods declared in the Collection interface. They are as follows:
Method Description
List Interface:
A List is an ordered Collection (sometimes called a sequence). Lists may contain
duplicate elements. Elements can be inserted or accessed by their position in the
list, using a zero-based index. The classes that implements List interface are:
ArrayList
LinkedList
Vector
Stack