Dictionary Meaning: Exception is an abnormal condition.
Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors.
Error: An Error indicates a serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
2. The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
Exception Handling in Java
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called
the exception object. It contains information about the exception, such as the name
and description of the exception and the state of the program when the exception
occurred.
Divyavani,Assistant Professor 2
3. Major reasons why an exception Occurs:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running
out of memory, memory leaks, stack overflow errors, library incompatibility, infinite
recursion, etc. Errors are usually beyond the control of the programmer, and we should
not try to handle errors.
differences between Error and Exception
Error: An Error indicates a serious problem that a reasonable application should not
try to catch.
Exception: Exception indicates conditions that a reasonable application might try to
catch.
Divyavani,Assistant Professor 3
4. Exception-Handling Fundamentals
A Java exception is an object that describes an exceptional (that is, error)
condition that has occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error.
That method may choose to handle the exception itself, or pass it on. Either
way, at some point, the exception is caught and processed.
Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code.
Divyavani,Assistant Professor 4
5. Java exception handling is managed via five keywords: try, catch, throw, throws,
and finally.
Program statements that you want to monitor for exceptions are contained within a
try block.
If an exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch) and handle it in some rational
manner.
System-generated exceptions are automatically thrown by the Java run-time
system.
To manually throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be specified as such by a throws
clause.
Divyavani,Assistant Professor 5
6. 1. try: The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
2. catch: The catch block is used to handle the uncertain condition of a try block. A
try block is always followed by a catch block, which handles the exception that
occurs in the associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
Divyavani,Assistant Professor 6
7. 3. throw: The throw keyword is used to transfer control from the try block
to the catch block.
4. throws: The throws keyword is used for exception handling without try
& catch block. It specifies the exceptions that a method can throw to the
caller and does not handle itself.
5. finally: It is executed after the catch block. We use it to put some
common code (to be executed irrespective of whether an exception has
occurred or not ) when there are multiple catch blocks.
Divyavani,Assistant Professor 7
8. This is the general form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed after try block ends
}
Divyavani,Assistant Professor 8
9. class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}
finally {
System.out.println("I am in final block");
}
}
} Divyavani,Assistant Professor 9
10. class ThrowsExecp {
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
// This is a caller function
public static void main(String args[])
{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("caught in main.");
}
}
}
Divyavani,Assistant Professor 10
12. throw, throws, and finally keywords in Java
throw keyword in Java
The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try blcok. When JVM encounters the throw keyword,
it stops the execution of try block and jump to the corresponding catch block.
Using throw keyword only object of Throwable class or its sub classes
can be thrown.
Using throw keyword only one exception can be thrown.
The throw keyword must followed by an throwable instance.
Syntax
throw instance;
Here the instace must be throwable instance
and it can be created dynamically using new
operator.
Divyavani,Assistant Professor 12
13. import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new
ArithmeticException("Division by zero is not
posible");
result = num1 / num2;
System.out.println(num1 + "/" + num2
+ "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the
program");
}
}
Divyavani,Assistant Professor 13
14. throws keyword in Java
The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically,
we use throws keyword followed by method declaration
🔔 When a method throws an exception, we must put the calling statement
of method in try-catch block.
import java.util.Scanner;
public class ThrowsExample {
int num1, num2, result;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException {
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" +
result);
}
public static void main(String[] args) {
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the
program");
}
}
Divyavani,Assistant Professor 14
15. Important Points to Remember about throws Keyword
throws keyword is required only for checked exceptions and usage of the
throws keyword for unchecked exceptions is meaningless.
throws keyword is required only to convince the compiler and usage of the
throws keyword does not prevent abnormal termination of the program.
With the help of the throws keyword, we can provide information to the caller
of the method about the exception.
Divyavani,Assistant Professor 15
16. finally keyword in Java
The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
🔔 Only one finally block is allowed for each try block.
🔔 Use of finally block is optional.
Rule: For each try block there can be zero or more catch blocks, but only one finally
block.
Note: The finally block will not be executed if the program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).
Divyavani,Assistant Professor 16
18. import java.util.Scanner;
public class FinallyExample {
public static void main(String[] args) {
int num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.print("Enter any two
numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new
ArithmeticException("Division by zero");
result = num1 / num2;
System.out.println(num1 + "/" + num2
+ "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " +
ae.getMessage());
}
finally {
System.out.println("The finally block
executes always");
}
System.out.println("End of the
program");
}
}
Divyavani,Assistant Professor 18
19. When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the
catch block cannot handle it. Despite this, the finally block is executed after the try block
and then the program terminates abnormally.
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try
block");
//below code throws divide by zero
exception
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception
occured or not
finally {
System.out.println("finally block is
always executed");
}
System.out.println("rest of the code...");
}
}
Divyavani,Assistant Professor 19
20. Sr. no. Basis of Differences throw throws
1. Definition Java throw keyword is used
throw an exception explicitly
in the code, inside the
function or the block of
code.
Java throws keyword is
used in the method
signature to declare an
exception which might be
thrown by the function while
the execution of the code.
2. Type of exception Using
throw keyword, we can only
propagate unchecked
exception i.e., the checked
exception cannot be
propagated using throw
only.
Using throws keyword, we
can declare both checked
and unchecked exceptions.
However, the throws
keyword can be used to
propagate checked
exceptions only.
3. Syntax The throw keyword is
followed by an instance of
Exception to be thrown.
The throws keyword is
followed by class names of
Exceptions to be thrown.
4. Declaration throw is used within the
method.
throws is used with the
method signature.
5. Internal implementation We are allowed to throw
only one exception at a time
i.e. we cannot throw
multiple exceptions.
We can declare multiple
exceptions using throws
keyword that can be thrown
by the method. For
example, main() throws
Divyavani,Assistant Professor 20
21. public class TestThrow {
//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("nNumber is negative, cannot
calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
} Divyavani,Assistant Professor 21
22. public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
} Divyavani,Assistant Professor 22
23. Exception Hierarchy
All exception and error types are subclasses of
class Throwable, which is the base class of the
hierarchy.
One branch is headed by Exception. This class is
used for exceptional conditions that user
programs should catch. NullPointerException is
an example of such an exception.
Another branch, Error is used by the Java run-
time system(JVM) to indicate errors having to do
with the run-time environment itself(JRE).
StackOverflowError is an example of such an
error.
Divyavani,Assistant Professor 23
25. Exceptions can be categorized in two ways:
1. Built-in Exceptions
a) Checked Exception
b) Unchecked Exception
2. User-Defined Exceptions
1. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
SQLException
DataAccessException
InstantiationException
Divyavani,Assistant Professor 25
26. import java.io.*;
public class CheckedExceptions {
public static void main(String[] args) {
File f_ref = new File("C:UsersUserDesktopTodaySample.txt");
try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}
}
}
Divyavani,Assistant Professor 26