0% found this document useful (0 votes)
4 views

Unit3 first half

Exception Handling in Java is a mechanism to manage runtime errors, allowing the program to maintain its normal flow. It involves the use of keywords like try, catch, finally, throw, and throws, and distinguishes between checked and unchecked exceptions. The document also explains the hierarchy of exceptions, differences between exceptions and errors, and provides examples of handling exceptions using various techniques.

Uploaded by

anuja.it
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit3 first half

Exception Handling in Java is a mechanism to manage runtime errors, allowing the program to maintain its normal flow. It involves the use of keywords like try, catch, finally, throw, and throws, and distinguishes between checked and unchecked exceptions. The document also explains the hierarchy of exceptions, differences between exceptions and errors, and provides examples of handling exceptions using various techniques.

Uploaded by

anuja.it
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

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:

Definition:1 A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.

Definition:2In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

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 application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. 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
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the
exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions
into two distinct branches. One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. This is also the class that you will subclass to create your
own custom exception types. There is an important subclass of Exception, called RuntimeException.
Exceptions of this type are automatically defined for the programs that you write and include things
such as division by zero and invalid array indexing. The other branch is topped by Error, which defines
exceptions that are not expected to be caught under normal circumstances by your program. Exceptions
of type Error are used by the Java run-time system to indicate errors having to do with the run-time
environment, itself. Stack overflow is an example of such an error.

Difference between Exception and Error in


Java
Exceptions and errors both are subclasses of Throwable class. The error indicates a problem that mainly occurs due
to the lack of system resources and our application should not catch these types of problems. Some of the examples
of errors are system crash error and out of memory error. Errors mostly occur at runtime that's they belong to an
unchecked type.
Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the
developers. Exceptions are divided into two categories such as checked exceptions and unchecked exceptions.

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception.

1. Checked Exception
2. Unchecked Exception
Difference between Checked and Unchecked Exceptions
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.

Java Exception Keywords


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

Keywor Description
d

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.
Java Exception Handling Example
Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.

JavaExceptionExample.java

1.
2. public class JavaExceptionExample{
3. public static void main(String args[]){
4. try{
5. //code that may raise exception
6. int data=100/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8. //rest code of the program
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable

, performing any operation on the variable throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string

variable that has characters; converting this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java try block


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


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Java catch block


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.

Java Multi-catch block


A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different exceptions,
use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block

Example 1

Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }
Test it Now

Output:

Arithmetic Exception occurs


rest of the code

Example 2

MultipleCatchBlock2.java

1. public class MultipleCatchBlock2 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7.
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Test it Now

Output:

ArrayIndexOutOfBounds Exception occurs


rest of the code

In this example, try block contains two exceptions. But at a time only one exception occurs and its
corresponding catch block is executed.
Example 3

In this example, we generate NullPointerException, but didn't provide the corresponding exception
type. In such case, the catch block containing the parent exception class Exception will invoked.

MultipleCatchBlock4.java

1. public class MultipleCatchBlock4 {


2. public static void main(String[] args) {
3.
4. try{
5. String s=null;
6. System.out.println(s.length());
7. }
8. catch(ArithmeticException e)
9. {
10. System.out.println("Arithmetic Exception occurs");
11. }
12. catch(ArrayIndexOutOfBoundsException e)
13. {
14. System.out.println("ArrayIndexOutOfBounds Exception occurs");
15. }
16. catch(Exception e)
17. {
18. System.out.println("Parent Exception occurs");
19. }
20. System.out.println("rest of the code");
21. }
22. }
Test it Now

Output:

Parent Exception occurs


rest of the code

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as nested try block. Every
statement that we enter a statement in try block, context of that exception is pushed onto the stack.

For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....

Java Nested try Example


Example 1
Let's see an example where we place a try block within another try block for two different exceptions.

NestedTryBlock.java

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}

Output:
When any try block does not have a catch block for a particular exception, then the catch block of the
outer (parent) try block are checked for that exception, and if it matches, the catch block of outer try
block is executed.

If none of the catch block specified in the code is unable to handle the exception, then the Java
runtime system will handle the exception. Then it displays the system generated message for that
exception.

Java finally block


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.

Why use Java finally block?


o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.

Usage of Java finally

When an exception occurs and is handled by the catch block

Example:
Let's see the following example where the Java code throws an exception and the catch block handles
the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code
is also executed normally.

TestFinallyBlock2.java

public class TestFinallyBlock2{


public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
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:

Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Java 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. 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. We will discuss custom exceptions later in this section.

We can also define our own set of conditions and throw an exception explicitly using throw keyword.
For example, we can throw ArithmeticException if we divide a number by another number. Here, we
just need to set the condition and throw exception using throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");

Java throw keyword Example


Example 1: Throwing Unchecked Exception

In this example, we have created a method named validate() that accepts an integer as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome
to vote.

TestThrow1.java

In this example, we have created the validate method that takes integer value as a parameter. If the
age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to
vote.

public class TestThrow1 {


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

Output:
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.

Note: If we throw unchecked exception from a method, it is must to handle the exception or declare in throws clause.

If we throw a checked exception using throw keyword, it is must to handle the exception using catch
block or the method must declare it using throws declaration.

Java throws keyword


The Java throws keyword is used to declare an exception. 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.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers' fault that he is not checking the code
before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Which exception should be declared?

Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

It provides information to the caller of the method about the exception.

Java throws Example


Let's see the example of Java throws clause which describes that checked exceptions can be
propagated by throws keyword.
Testthrows1.java

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Test it Now

Output:

exception handled
normal flow...

The following are the important differences between throw and throws.

Sr. No. Key throw throws

Definition Throw is a keyword which is used Throws is a keyword used in the method
to throw an exception explicitly in signature used to declare an exception
1
the program inside a function or which might get thrown by the function
inside a block of code. while executing the code.

Internal Internally throw is implemented as On other hand we can declare multiple


implementatio it is allowed to throw only single exceptions with throws keyword that could
2 n exception at a time i.e we cannot get thrown by the function where throws
throw multiple exception with keyword is used.
throw keyword.

Type of With throw keyword we can On other hand with throws keyword both
exception propagate only unchecked checked and unchecked exceptions can be
3 exception i.e checked exception declared and for the propagation checked
cannot be propagated using exception must use throws keyword
throw. followed by specific exception class name.

Syntax Syntax wise throw keyword is On other hand syntax wise throws keyword
4
followed by the instance variable. is followed by exception class names.

Declaration In order to use throw keyword we On other hand throws keyword is used with
5 should know that throw keyword the method signature.
is used within the method.
Java Built-in Exception

Inside the standard package java.lang, Java defines several


exception classes. The most general of these exceptions are subclasses of the
standard type RuntimeException

In the language of Java, these are called unchecked exceptions because the compiler does
not check to see if a method handles or throws these exceptions. The unchecked exceptions

defined in java.lang are listed in Table 10-1 . Table 10-2 lists those exceptions defined by
java.lang that must be included in a method’s throws list if that method can generate one of
these exceptions and does not handle it itself. These are called checked exceptions.
Java Custom Exception/User Defined Exception
In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our
own Exception is known as custom exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user need.

Consider the example 1 in which InvalidAgeException class extends the Exception class.

Using the custom exception, we can have your own exception and message. Here, we have passed a
string to the constructor of superclass i.e. Exception class that can be obtained using getMessage()
method on the object we have created.

Why use custom exceptions?


Java exceptions cover almost all the general type of exceptions that may occur in the programming.
However, we sometimes need to create custom exceptions.

In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.

Note: We need to write the constructor that takes the String as the error message and it is called parent class constructor.

Example 1:

Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of parent class
Exception using the super() method. Also the constructor of Exception class can be called without
using a parameter and calling super() method is not mandatory.

TestCustomException1.java
1. // class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("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 (InvalidAgeException 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:

You might also like