0% found this document useful (0 votes)
17 views18 pages

UNIT-2 Exception Handling

The document provides an overview of exceptions in Java, explaining their definition, causes, and types, including built-in and user-defined exceptions. It also discusses exception handling mechanisms such as try-catch blocks, the use of keywords like throw and throws, and the differences between errors and exceptions. Additionally, it includes examples illustrating exception handling and the importance of managing exceptions in Java programming.

Uploaded by

nikitaaatyagi27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views18 pages

UNIT-2 Exception Handling

The document provides an overview of exceptions in Java, explaining their definition, causes, and types, including built-in and user-defined exceptions. It also discusses exception handling mechanisms such as try-catch blocks, the use of keywords like throw and throws, and the differences between errors and exceptions. Additionally, it includes examples illustrating exception handling and the importance of managing exceptions in Java programming.

Uploaded by

nikitaaatyagi27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-2 NOTES

OF
OOPS
What is 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.

In Java, 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.

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.

Difference between Error and Exception


Let us discuss the most important part which is the differences between
Error and Exception that is as follows:
 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.
Types of Exceptions
Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
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.

 Unchecked Exceptions: The unchecked exceptions are just opposite to


the checked exceptions. The compiler will not check these exceptions at
compile time. In simple words, if a program throws an unchecked
exception, and even if we didn’t handle or declare it, the program would
not give a compilation error.
Note: For checked vs unchecked exception, see Checked vs Unchecked
Exceptions
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called
‘user-defined Exceptions’.
Why does an exception occur?

The key point here is possibility. There are multiple things that could go wrong.
Network state, user interaction, invalid inputs, etc., are some of the things which
could lead to an exception. What’s important is how you handle those exceptions
which you think will occur sometime in some way or the other.

Exception Handling by JVM


When an exception occurs inside a java program, an object is created which
describes the exception, including its type and state of the program when it
occurred. This object is then passed to the Java Virtual Machine (JVM). The JVM tries
to find a method or function to handle the exception. It goes through a list of
methods that can potentially handle the exception.

Once it finds the appropriate method to handle the exception, it hands over the
exception to the method, but if it can’t find an appropriate method, it terminates the
program by calling the default exception-handling method.
Ways to Handle an Exception
Here are some ways in which you can handle or throw an exception:

 try… catch block


 throw/throws keyword

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

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

OUTPUT
Exception in thread main [Link]:/ by zero
rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-


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

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.
Let's see a simple example of java multi-catch block.

[Link]

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. [Link]("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. [Link]("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. [Link]("Parent Exception occurs");
20. }
21. [Link]("rest of the code");
22. }

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.

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.
[Link]

1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. [Link](data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. [Link](e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. [Link]("finally block is always executed");
15. }
16.
17. [Link]("rest of phe code...");
18. }
19. }

Output:

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.
[Link]

1. public class TestFinallyBlock1{


2. public static void main(String args[]){
3.
4. try {
5.
6. [Link]("Inside the try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. [Link](data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. [Link](e);
16. }
17.
18. //executes regardless of exception occured or not
19. finally {
20. [Link]("finally block is always executed");
21. }
22. [Link] ("rest of the code...");
23. }
24. }

Output:
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.

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. [Link]("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. [Link]("rest of the code...");
17. }
18. }

Output:

Java throws keyword


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.
public class TestThrows {

public static int divideNum(int m, int n) throws ArithmeticException {

int div = m / n;

return div;

public static void main(String[] args) {

TestThrows obj = new TestThrows();

try {

[Link]([Link](45, 0));

catch (ArithmeticException e){

[Link]("\nNumber cannot be divided by 0");

[Link]("Rest of the code..");

}
1->This is the basic example of Exception handling,here exception is caught by
catch. And other method is executed as it is.

class Ex

void add()

int a=32,b=4;

[Link](a+b);

public static void main(String args[])

try

int i=6;

int j=i/0;

catch(ArithmeticException ex)

{ [Link]("Exception arise is"+" "+ex);

Ex e=new Ex();

[Link]();

[Link]("rest of application code");

2->This is the example of all exception classes are inside of catch block
sequence is matter sub classes and at last super class is there. Exception is
super class and rest of are sub [Link] exception occurs inside of try
block then all line are skipped of try block after exception caught then control
goes to catch block.

class test1

public static void main(String args[])

try

int i=6;

int j=i/0;

String s=null;

[Link](j);

[Link]([Link]());

catch(ArithmeticException ex)

[Link]("Exception arises"+ex);

catch(NullPointerException ex)

[Link]("Exception arises"+ex);

catch(ArrayIndexOutOfBoundsException ex)

[Link]("Exception arises"+ex);
}

catch(Exception ex)

[Link]("Exception arises"+ex);

[Link]("rest of code");

4-> this is the example of nested try catch block.


class test5

public static void main(String args[])

try

int i=6;

String x=null;

[Link]([Link]());

try

int j=i/0;

[Link](j);

catch(ArithmeticException ex)

[Link]("Exception"+ex);

[Link]("hiii");

catch(NullPointerException ex)

[Link]("Exception"+ex);

[Link]("nested try catch block");


}

3-> In this example reverse order of exception classes is not applicable, error
occurs bcoz we write Exception class(Parent class firstly).

class test

public static void main(String args[])

int a=[Link](args[0]);

int b=[Link](args[1]);

try

int c=a/b;

String x=null;

[Link]([Link]());

[Link](c);

[Link]("no exception");

}
catch(Exception ex)

[Link]("Exception arise is"+ex);

catch(ArithmeticException ex)

[Link]("Exception arise is"+ex);

catch(NullPointerException ex)

[Link]("Exception arise is"+ex);

[Link]("hello");

}
Difference between throw and throws keyword->

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword Java throws keyword is


is used throw an used in the method
exception explicitly signature to declare an
in the code, inside exception which might
the function or the be thrown by the
block of code. function while the
execution of the code.

2. Type of exception Using Using throws


throw keyword, we can keyword, we can
only propagate declare both
unchecked exception checked and
i.e., the checked unchecked
exception cannot be exceptions. However,
propagated using throw the throws keyword
only. can be used to
propagate checked
exceptions only.

3. Syntax The throw keyword The throws keyword is


is followed by an followed by class
instance of names of Exceptions
Exception to be to be thrown.
thrown.

4. Declaration throw is used within throws is used with the


the method. method signature.

5. Internal implementation We are allowed to We can declare


throw only one multiple exceptions
exception at a time using throws keyword
i.e. we cannot throw that can be thrown by
multiple exceptions. the method. For
example, main()
throws IOException,
SQLException.

You might also like