0% found this document useful (0 votes)
34 views14 pages

Java Exception Handling Notes

The document discusses exception handling in Java, including the different types of exceptions, keywords used for handling exceptions like try, catch, finally and throw, and provides examples of exception handling code.

Uploaded by

laptop90081
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
34 views14 pages

Java Exception Handling Notes

The document discusses exception handling in Java, including the different types of exceptions, keywords used for handling exceptions like try, catch, finally and throw, and provides examples of exception handling code.

Uploaded by

laptop90081
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

BCA – 401: Java Programming

Rahul Kumar Singh


In today's Class we have discussed on Exception Handling
in Java.
Exception Handling:-
Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc so that the normal
flow of the application can be maintained.

Exception in Java:-
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at
runtime.

Advantage of Exception Handling:-


The core advantage of exception handling is to maintain
the normal flow of the application. An exception normally
disrupts the normal flow of the application; that is why we
need to handle exceptions.
Example:- Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in a Java program and an


exception occurs at statement 5; the rest of the code will
not be executed, i.e., statements 6 to 10 will not be
executed. However, when we perform exception handling,
the rest of the statements will be executed. That is why we
use exception handling in Java.

Hierarchy of Java Exception classes:-


The java.lang.Throwable class is the root class of Java
Exception hierarchy inherited by two subclasses: Exception
and Error. The hierarchy of Java Exception classes is given
below:
Types of Java Exceptions:-
There are mainly two types of exceptions: checked and
unchecked. An error is considered as the unchecked
exception. However, according to Oracle, there are three
types of exceptions namely:
1)Checked Exception
2)Unchecked Exception
3)Error
1) Checked Exception:-
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked
exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception:-
The classes that inherit the RuntimeException are known
as unchecked exceptions. For example,
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are
checked at runtime.
3) Error:-
Error is irrecoverable. Some example of errors are
OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords:-
Java provides five keywords that are used to handle the
exception.
try keyword:- 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.
Java try block is used to enclose the code that might throw
an exception. It must be used within the method.
If an exception occurs at the particular statement in the try
block, the rest of the block code will not execute. So, it is
recommended not to keep the code in try block that will not
throw an exception.
Java try block must be followed by either catch or finally
block.
Syntax of Java try-catch
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
Syntax of try-finally block
try
{
//code that may throw an exception
}
finally
{
}
catch keyword:- 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.
Java catch block is used to handle the Exception by
declaring the type of exception within the parameter. The
declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the
good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You
can use multiple catch block with a single try block.
Example try catch:-
public class TryCatchExample
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:-
java.lang.ArithmeticException: / by zero
rest of the code
finally keyword:- The "finally" block is used to execute the
necessary code of the program. It is executed whether an
exception is handled or not.
Java finally block is a block used to execute important
code such as closing the connection, etc.
Java finally block is always executed whether an exception
is handled or not. Therefore, it contains all the necessary
statements that need to be printed regardless of the
exception occurs or not.
The finally block follows the try-catch block.
Example:-
public class TestFinallyBlock
{
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);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
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...");
}
}
Output:-
Inside the try block
finally block is always executed
java.lang.ArithmeticException: / by zero
throw keyword:- The "throw" keyword is used to throw an
exception.
We specify the exception object which is to be thrown. The
Exception has some message with it that provides the error
description. These exceptions may be related to user
inputs, server, etc.
We can throw either checked or unchecked exceptions in
Java by throw keyword. It is mainly used to throw a custom
exception.
Syntax:-
throw new exception_class("error message");
Example:-
throw new IOException("sorry device error");
Example 1: Throwing Unchecked Exception
public class TestThrow
{
//function to check if person is eligible to vote or not
public static void validate(int age)
{
if(age<18)
{
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not
eligible to vote");
}
else
{
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[])
{
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

throws keyword:- 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. It gives an information to the
programmer that there may occur an exception. So, it is
better for the programmer to provide the exception
handling code so that the normal flow of the program can
be maintained.
Syntax of Java throws:-
return_type method_name() throws exception_class_name
{
//method code
}
Example:-
import java.io.IOException;
class Testthrows
{
void m()throws IOException
{
//checked exception
throw new IOException("device error");
}
void n()throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
public static void main(String args[])
{
Testthrows obj=new Testthrows();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...

Java Exception Handling Example:-


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...");
}
}
Output:-
Exception in thread main java.lang.ArithmeticException:/ by
zero
rest of the code...

You might also like