100% found this document useful (1 vote)
67 views

Exception Handling

This document discusses exception handling in Java. It defines an exception as an error that disrupts normal program flow. There are three types of exceptions in Java: checked exceptions which must be handled at compile time, unchecked exceptions which occur at runtime, and errors which cannot typically be handled. The try-catch block is used to handle exceptions gracefully and allow code execution to continue past the point of failure. Finally blocks are used to execute cleanup code regardless of exceptions.

Uploaded by

Madhu Sudhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
67 views

Exception Handling

This document discusses exception handling in Java. It defines an exception as an error that disrupts normal program flow. There are three types of exceptions in Java: checked exceptions which must be handled at compile time, unchecked exceptions which occur at runtime, and errors which cannot typically be handled. The try-catch block is used to handle exceptions gracefully and allow code execution to continue past the point of failure. Finally blocks are used to execute cleanup code regardless of exceptions.

Uploaded by

Madhu Sudhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Exception Handling in Java

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.

 A user has entered an invalid data.


 The number is divided by zero.
 A file that needs to be opened cannot be found.Etc
Some of these exceptions are caused by user error, others by programmer
error, and others by physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions.

Types of Java Exceptions:


there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

1. Checked exceptions: A checked exception is an exception that is


checked (notified) by the compiler at compilation-time, these are also
called as compile time exceptions. These exceptions cannot simply be
ignored, the programmer should take care of (handle) these
exceptions. E.g: IOException, SQLException,FileNotFoundException
etc.

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

2. Unchecked exceptions:An unchecked exception 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.
Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
For example, if you have declared an array of size 5 in your program, and
trying to call the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexception occurs.

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.

A hierarchy of Java Exception classes are given below:


What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of


the execution. An exception normally disrupts the normal flow of the
execution of the program and terminate the program abnormally, that is why
we use exception handling. Let's take a scenario:

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 Exception Keywords

Java provides five keywords that are used to handle the exception. The
following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we


should place an exception code. It means we can't use try block
alone. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must


be preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of
the program. It is executed whether an exception is handled or
not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It


specifies that there may occur an exception in the method. It
doesn't throw an exception. It is always used with method
signature.

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

public class JavaExceptionExample


{
public static void main(String args[])
{
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...");
}
}

Following is a list of most common checked and unchecked Java's Built-in


Exceptions.
Java defines several other types of exceptions that relate to its various class
libraries.

Following is the list of Java Unchecked RuntimeException.

Sl.No. Exception & Description


ArithmeticException
1
Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException
2
Array index is out-of-bounds.
ArrayStoreException
3
Assignment to an array element of an incompatible
type.
IllegalArgumentException
4
Illegal argument used to invoke a method.
IllegalStateException
5
Environment or application is in incorrect state.
IllegalThreadStateException
6
Requested operation not compatible with the current
thread state.
IndexOutOfBoundsException
7
Some type of index is out-of-bounds.
NegativeArraySizeException
8
Array created with a negative size.
NullPointerException
9
Invalid use of a null reference.
NumberFormatException
10
Invalid conversion of a string to a numeric format.
SecurityException
11
Attempt to violate security.
StringIndexOutOfBounds
12
Attempt to index outside the bounds of a string.
UnsupportedOperationException
13
An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in java.lang.

Sl.No. Exception & Description


1 ClassNotFoundException
Class not found.
2 CloneNotSupportedException
Attempt to clone an object that does not implement
the Cloneable interface.
3 IllegalAccessException
Access to a class is denied.
4 InstantiationException
Attempt to create an object of an abstract class or
interface.
5 InterruptedException
One thread has been interrupted by another thread.
6 NoSuchFieldException
A requested field does not exist.
7 NoSuchMethodException
A requested method does not exist.

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.");
}
}

This will produce the following result −


Output:
Division by zero.
After catch statement.

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple
catch blocks looks like the following −
Syntax
try {
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3)
{
// Catch block

}
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.

We specify the exception object which is to be thrown. The Exception has


some message with it that provides the error description.

We can throw either checked or unchecked exceptions in Java by throw


keyword. It is mainly used to throw a custom exception.

The syntax of the Java throw keyword is given below.


throw throwableObject;

A throwableobject is an instance of class Throwable or subclass of


the Throwable class.
Example:
throw new ArithmeticException("/ by zero");

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or


older, print "Access granted":

public class Main


{
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18
years old.");
}
else
{
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args)


{
checkAge(15);
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: Access denied - You


must be at least 18 years old.

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:

type method-name(parameter-list) throws exception-list


{
// body of method
}

Example throws Keyword

Here, we have a method that can throw Arithmetic exception so we mentioned


that with the method declaration and catch that using the catch handler in the
main method.

class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String args[])


{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}

Output:
Inside check function
caughtjava.lang.ArithmeticException: demo
Difference between throw and throws

throw throws

throws keyword is used to


throw keyword is used to throw declare an exception possible during its
an exception explicitly. execution.

throw keyword is followed by an throws keyword is followed by one


instance of Throwable class or one of or more Exception class names
its sub-classes. separated by commas.

throw keyword is declared throws keyword is used with


inside a method body. method signature (method declaration).

We can declare multiple


We cannot throw multiple
exceptions (separated by commas) using
exceptions using throw keyword.
throws keyword.

Finally Block:
The finally block follows a try block or a last catch block.

A finally block of code always executes, irrespective of occurrence of an


Exception.

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.

A finally contains all the crucial statements regardless of the exception


occurs or not.
Syntax
try {
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3)
{
// Catch block
}
Finally
{
// The finally block always executes.
}

There are 3 possible cases where finally block can be used:


Case 1: When an exception does not rise
In this case, the program runs fine without throwing any exception and finally
block execute after the try block.
import java.io.*;

class GFG {
public static void main(String[] args)
{
try {
System.out.println("inside try block");

// Not throw any exception


System.out.println(34 / 2);
}

// Not execute in this case


catch (ArithmeticException e) {

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 {

public static void main(String[] args)


{
try {
System.out.println("inside try block");

// Throw an Arithmetic exception


System.out.println(34 / 0);
}

// catch an Arithmetic exception


catch (ArithmeticException e) {

System.out.println(
"catch : exception handled.");
}

// Always execute
finally {

System.out.println("finally : i execute always.");


}
}
}
Output
inside try block
catch : exception handled.
finally : i execute always.

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");

// Throw an Arithmetic exception


System.out.println(34 / 0);
}

// Can not accept Arithmetic type exception


// Only accept Null Pointer type Exception
catch (NullPointerException e) {

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.

We can define our own Exception class as below −

class MyException extends Exception


{

You just need to extend the predefined Exception class to create your own
Exception. These are considered to be checked exceptions.

Example:

class MyException extends Exception


{
MyException (String str)
{
// calling the constructor of parent Exception
super(str);
}

// method to check the age


static void validate (int age) throws MyException{
if(age < 18){

// throw an object of user defined exception


throw new MyException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (MyException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException


object System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}

Output:

F:\java>java MyException

Caught the exception

Exception occured: MyException: age is not valid to vote

rest of the code...


Collections in Java:

The Java Collections Framework is a collection of interfaces and classes, which


helps in storing and processing the data efficiently. This framework has several
useful classes which have tons of useful functions which makes a programmer
task easy.

Hierarchy of Collection Framework


Iterator interface

Iterator interface provides the facility of iterating the elements in a forward


direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:

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.

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

Method Description

add(object e) It is used to insert an element in this collection.

remove(Object It is used to delete an element from the collection.


element)

size() It returns the total number of elements in the


collection.

clear() It removes the total number of elements from the


collection.

contains(Object It is used to search an element.


element)

public Iterator It returns an iterator.


iterator()

public Object[] It converts collection into array.


toArray()

isEmpty() It checks if collection is empty.

equals(Object element) It matches two collections.

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

You might also like