0% found this document useful (0 votes)
14 views55 pages

Java Exception Handling Overview

Uploaded by

roopakuruba55
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)
14 views55 pages

Java Exception Handling Overview

Uploaded by

roopakuruba55
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

wthat a an exceptten

?S
-txplao the 5 eywodA atoclated
sith Exception ttandllEne
& eapton hendliy
De<ioe exepboo
Symta &Cateb
Eanple o try
5
Catch ,thzoOa,
Catch ,th ffnally
ry, Throw,
Exception Handling
Exception: An Exception is an abnormal condition that arises in a code sequence at run
time. That is, an exception is a run-time erOr.
It's a problem that arises during the execution of a program.
Ex: User entered invalid data.
File not found

Exception Handling: Handling errors during execution of a program is known as


Exception
Handling.
NOTE: Exception handling is a task to maintain Normal flow of the
program. Exception
handling does not mean repairing an exception, it is rather defining
alternative way to
continue rest of the program normally.
> 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
block. If an exception occurs within the try block, it is thrown.
>Your code can catch this exception (using catch) and handle it.
> 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.
> Any code that absolutely must be executed after a try block completes is put in a finally
block.
General Form

This is the general form of an exception-handling block:


try
/ block of code to monitor for errors

catch (ExceptionTypel exOb) {


ll exception handler for ExceptionTypel

exOh) / p Dit, C
Cch (ExceptionType2
lexception handler for ExceptionType2

finally {
/ block of code to be executed after try block ends
OR YOU CAN WRITE THIS
Exception handling
An Exception, it can be defined as an abnormal event that occurs during program execution and
disrupts the normal flow of instructions. The abnormal event can be an eror in the program.

Errors in a java program are categorized into two groups:


1. Compile-time errors occur when you do not follow the syntax of aprogramming language.
2. Run-time errors occur during the execution of a program.

Concepts of Exceptions
An exception is a run-time error that occurs during the exception of a java program.
Example: If you divide a number by zero or open a file that does not exist, an exception is
raised.

In java, exceptions can be handled either by the java run-time system or by a user-defined code.
When a run-time error occurs, an exception is thrown.

The unexpected situations that may occur during program execution are:
/ Running out of memory
Resource allocation erors

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 27


Exception handling techniques:
Java exception handling is managed via five keywords they are:
1. try
2. catch
3. throw
4. throws
5. finally

Exception handling Statement Syntax


Exceptions are handled using a try-catch-finally construct, which has the Syntax
try

<code>

catch (<exception typel> <parameterl>)

1/ 0 or more<statements>

finally

1/ finally block<statements> 28/39


Exception handling Statement Syntax
Exceptions are handled using a try-catch-finally construct, which has the Syntax
try

<code>

catch (<exception typel> <parameterl>)

1/0 or more<statements>

finally

1/ finally block<statements>

1. try Block: The java code that you think may produce an exception is placed within a try block
for a suitable catch block to handle the error.

If no exception occurs the execution proceeds with the finally block else, it will look for
the matching catch block to handle the eror.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 28

Object Oriented Concepts -21CS32


Again if the matching catch handler is not found execution proceeds with the finally
block and the default exception handler throws an exception.
2. catch Block: Exceptions thrown during execution of the try block can be caught and handled
in a catch block. On exit froma catch block, normal execution continues and the finally block is
executed (Though the catch block throws an exception).
3. finally Block: A finally block is always executed, regardless of the cause of exit from the try
block, or whether any catch block was executed. Generally. finally block is used for freeing
resources, cleaning up, closing connections etc.
throw Keyword
throw keyword is used to throw an exception explicitly.
Only object of Throwable class or its sub classes can be thrown.
Program execution stops on encountering throw statement, and the closest catch
statement is checked for matching type of exception.

Syntax : throw ThrowableInstance


throws Keyword
Any method capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method getsa prior knowledge about which exceptions to
handle. A method can do so by using the throws keyword.

Syntax :
type method_name(parameter_list) throws exception_list
I/definition of method
[Link] BETWEEN CHECKED
AND UNCHECKED EXCEPTIONS

Checked Exception Unchecked Exception

Checked exceptions Unchecked exceptions


occur at compile time. OCcur at runtime.

The compiler checks a The compiler does not


checked exception. check these types of
exceptions.

These types of These types of


exceptions can be exceptions cannot be a
handled at the time of catch or handle at the
compilation. time of compilation,
because they get
generated by the
mistakes in the
program.

They are the sub-class They are runtime


of the exception class. exceptions and hence
are not a part of the
Exception class.
Here, the JVM needs Here, the JVM does not
the exception to catch require the exception
and handle. to catch and handle.

Examples of Checked Examples of

No Such Field Undeclared


Exception Throwable

Interrupted Exception
Exception Empty Stack
No Such Method Exception
Exception Arithmetic

Class Not Found Exception


Exception Null Pointer
Exception
Array Index Out of
Bounds Exception
Security
Exception
13 DIFFERENCE BETWEEN
METHOD OVER LOADING AND
OVERRIDING
6.0
51.0

Difference between Overloading and Overriding


SN Method Overloading Method Overriding
polymorphismISa
Method overlo compile-time Method ngis a run-time
polymor
It occurs within the class. It is performed in two classes with
inheritance relationships.
3 Method overloading may or may not Method overriding always nceds
require inheritance. inheritance.
In method overloading, methods must have In method overriding,methods must
the same name and different signatures. have the same name and same signature.
5 In method overloading, the return type can In method overriding, the return type
or cannot be the same, but we just have to must be the same or co-variant.
change the parameter.
6 Static binding is being uscd for overloaded Dynamic binding is being used for
methods. overriding methods.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 20

Object Oriented Concepts -21CS32


7 It gives better performance. The reason Poor performance
behind this is that the binding of
overridden methods is being done at
runtime.
Private and final methods can be Private and final methods can't be
overloaded. overridden.
9 Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
Method Overloading Method Overriding

Method overloading is a compile-time polymorphism Method overriding is a run-time polymorphism

Method overloading helps to increase the readability of the program. Method overriding is used to grant the specific implementation of the method which is
already provided by its parent dass or superdass.

It occurs within the cdass. It is performed in two classes with inheritance relationships.

Method overloading may or may not require inheritance. Method overriding always needs inheritance.

In method overloading, methods must have the same name and different signatures. In method overriding, methods must have the same name and same signature.

In method overloading, the return type can or can not be the same, but we just have to n method
overriding, the return type must be the same or co-variant.
change the parameter.
In method overloading, methods must have the same name and different signatures. In method overriding, methods must have the same name and same signature.

In method overloading, the return type can or can not be the same, but We
just nave to n method overriding. the return type must be the same or
change the parameter. co-Variant.

Static binding is being used for overloaded methods. Dynamic binding is being used for overiding methods.

Poor Performance due to compile time polymorphism It gives better performance. The reason behind this is that the binding of overridden
methods is being done at runtime.

Private and final methods can be overloaded. Private and final methods can't be overridden.

The argument list should be different while doing method overloading. The argument list should be the same in method overriding.
METHODOVERLOADING
class Overloading Example {
I/ Method with two integer parameters
int add(it a, int b) {
return a + b;
}

II Method with three integer parameters


(overloaded)
int add(int a, int b, int c) {
return a+b+ c;
}
I/ Method with two double parameters (overloaded)
double add(double a, double b) {
return a + b;

public static void main(Stringl] args) {


OverloadingExample obj = new
OverloadingExample():
[Link]("Sum of two integers: " +
[Link](5, 10);
[Link] ("Sum of three integers: +

[Link] (5, 10, 15):


[Link]("Sum of two doubles:" +
[Link](5.5, 10.5));
METHOD OVERRIDING
class Animal {
void sound() {
[Link]("Animal makesa sound");

class Dog extends Animal {


I| Overriding the sound method in the subclass
void sound() (
[Link]("Dog barks");
}

class Cat extends Animal {


I/ Overriding the sound method in the subclass
void sound() {
[Link] ("Cat meows");

public class OverridingExamplel


public static void main(Stringl] args) {
Animal animal1 = new Dog():
Animal animal2 = new Cat():

I| Calls the overridden method based on the


actual object type
[Link]):
[Link] ():
he syntax o ty , Catch btock
Wait xplain?
tohonde nultiple cxapttons.
Multiple catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:
try

| | code
)
catch (BxceptionTypel el)

1/Cat ch block

catch (ExceptionType2 e2)

1/Catch block

catch (ExceptionType3 e3)


{
1/Catch block

The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try.
Example: Here is code segment showing how to use multiple try/catch statements
try

1/ statements

catch (<exception> obj)


1| statements

finally
1/statements

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 36

Object Oriented Concepts -21CS32


Take a look at the following example which has a catch and a finally block. The catch block
catches the ArithmeticException which occurs for arithmetic error like divide-by-zero. After
executing the catch block the finally is also executed and you get the output for both the blocks.
class Finally_Block
{
static void division ()

try

int num = 34, den = 0;


int quot = num / den;

catch (ArithmeticException e)

System. out .println ("Divide by zero") :


finally

System. [Link] (" In the finally block") ;

class Mypgm

public static void main (String args[1)


Finally Block f=new Finally_Block () :
[Link]
Example: Here is code segment showing how to use multiple try/catch statements
class Multi Cat ch

public static void ma in (String args [1)

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 30

Object Oriented Concepts -21CS32


try

int a=args. length;


System. [Link]("a="ta) ;
int b=50/a;

int c[]={1)
)
catch (ArithmeticException e)

[Link] ("Division by zero") :

catch (ArrayIndexOutOfBoundsException e)

System. [Link] (" array index out of bound") ;

OUTPUT 31/39
Division by zero
array index out of bound
Multiple Catch Clause
Multiple catch Clauses
> In some cases, more than one exception could be raised by asingle piece of code.
º To handle this type of situation, you can specify two or more catch clauses, each
catching adiferent type of exception.
> When an exception is thrown, each catch statement is inspected in order, and the fir
one whose type matches that of the exception is executed.
º After one catch statement executes, the others are bypassed, and execution continue
after the try-catch block.
> Ex: TryCatch4. java

Example

I/ Demonstrate multiple catch statements.


class MultiCatch

public static void main(String args[ ))


{ This program will cause a divisic
try zero exce ption if it is storted wi
commandline arguments, since
int a equal zero.

[Link]+
System. out.
int b = 42 / a;
int d) = {1;
o;
It will survive the division if you p
a comma nd-line argument, sett
q42) = 99, to something larger than zero.
}catch(ArithmeticException e) { But it ill couse an
System. out. printinDivide by O: "+ e);
}catch(AraylndexOutOfBoundsException e) ArrayindexOutOfBoundsExceptior
since the int array c has a length
System. out. printin("Array index oob: "+ e); yet the program
attempts to assign a value to c
System. out. printin("After try/catch blocks. ")
explavio the
what ts a Conbuctos
) Sutta b s crample
hoetr
Conept
Constructors
It can be tedious to initialize all the variables in a class each time an instance is created.
Even when you add convenience functions like getdata ), it would be simpler and more
concise to have all the setuup done at the time the object is first created.
Because the requirement for initialization is so common, Java allows objects to initialize
themselves when they are aeated. This automatic initialization is perfomed through use of
0constructor.

A constructor initializes an object immediately upon creotion It has the same name as
the dass in which it resides and is syntactically similar to method.
" Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
"Constructors look a little strange because they have no return type, not even void This is
because the implicit retum type of a cass' constructor is the class type itself.
You can rework the Box example so that the dimensions of a box are auto matically
initialized when an object is constructed.

" Rules for creating Java constructor


" There are two rules defined for the constructor.
Constructor name must be the same as itsclass name
" A
Constructor must have no explicit return type
" A Java constructor cannot be abstract, static, final, and synchronized
Note: It is called constructor because it constructs the values at the time of
object creation. It is not necessary to write a constructor for a class It is
because java compiler creates a default constructor if your class do esn't have
any.
/Here, Bax uses a constructor to initialize the
"dimensions of a box.
class Box
double width
double height;
double depth
I This is the constructor for Box.
Box)
System out printin("Constructing Bo:
"width 10,
height 10:
depth

l compute and return voume


double volume() {
retum width height depth,

class Box Demo6 {


public stotic void moin(String orgsD {
Hdeclare, allocate, and initilize Bax objects
Box myboxnewBox0
Boxmybox2nex Box)
double vol;
l get volume of first box
vol myboxt. volume
System out. prirtir(Volume is vo
Iget volume of second box
" volmybox2. volumek
System out. prirtin("Volume is" vol

When thisprogromis un it generates the folowing results:


Constructing Box
Constructing Box
" Volume is 1000,o
Volume is 1000.O
class BoxDemo6 (
public sttic void main(String args) {
H declare, allocate, and initialize Box objects
Box mybox new BoxO
Boxmybox2new BoxC
double vol;
H get volume of fist bax
vol myboxt. volumeo;
System [Link](Volume is"+ vol)
Il get volume of second box
volmybox2. volume
System cut. printir(Volume is vol)

When this programis un, it gererates the following results:


Constructing Box
Constructing Box
Volume is 1000, O
Volume is 1000.0

. As you can see, both myboxi and mybox2 were initialized by the Box( ) constructor when
they were created.
Since the constructor gives all boxes the same dimensions, 1O by 10 by 10, both myboxi and
mybox2 will have the same volume.
" The println( ) statement inside Box( ) is for the sake of illustration only. Most constructors
will not displey anything They will simplyinitializean object
.Before moving on, let's reexamine the new operator. As you know, when you allocate an
object, you use the follbwing general fom:
class-var = new classname)
. Now you can understand why the parentheses are needed after the class name. What is
actually happening is that the constructor for the class is being called. Thus, in the line
Box mybox =new Box0:
. new Box() is caling the Box( ) constructor. When you do not explicitly define a constructor
for a class, then Java reatesa default constructor for the dass.
. This is why the preceding line of code worked in eartier versions of Box that did not define a
constructor. The default constructor automatically initializes all instance variables to zero.

Common questions

Powered by AI

Java constructors are special methods used to initialize new objects and have some specific rules: the constructor name must match the class name, and it must not have an explicit return type . Java constructors cannot be abstract, static, final, or synchronized. Constructors help set up the initial state of an object when it is created, automatically invoking any necessary setup when an instance of a class is instantiated . For instance, in the Box class, a constructor is used to initialize the dimensions of the box (width, height, depth) to predefined values upon creation . When a constructor is not explicitly defined, Java provides a default constructor that initializes objects with default states, ensuring that all Java objects are properly initialized when created . Constructors primarily assist in encapsulating object setup logic, helping create a predictable and usable state of objects at instantiation.

The main goal of exception handling in Java is to maintain the normal flow of the program in the face of run-time errors . The keyword 'try' is used to define a block of code that is monitored for exceptions . The 'catch' keyword is utilized to handle specific exceptions that may arise within the try block, allowing the program to continue its execution unless a catch block is not found for a raised exception . The 'throw' keyword enables the explicit throwing of exceptions, facilitating custom error handling beyond those automatically generated by the JVM . 'Throws' is used to declare the exceptions that a method can raise, giving calling methods prior knowledge of possible exceptions to handle . The 'finally' block always executes after try and catch blocks, often used for cleanup activities like freeing resources, ensuring that necessary code runs regardless of exceptions . Together, these keywords create a robust mechanism for handling errors by separating error processing code from regular code and determining the program's flow during exceptions.

The 'finally' block in Java plays a crucial role in ensuring consistent program termination by providing a guaranteed section of code that executes regardless of whether an exception is raised or caught in the preceding try or catch blocks . This guarantees that certain operations, such as resource deallocation, closing file streams, or releasing locks, are executed without fail, even if unexpected errors disrupt normal flow . Its reliability comes from ensuring that cleanup happens consistently, helping avoid resource leaks or system instabilities that can occur if resources are not properly closed or freed. As such, the 'finally' block adds a layer of resilience and robustness to the code, improving the overall stability and maintainability of Java applications by ensuring that critical cleanup operations are performed before the program exits, regardless of how it exits.

Multiple catch blocks in Java allow handling of different exceptions that might arise from a single try block. When an exception is thrown within the try block, the catch statements are inspected in order, and the first one matching the type of the exception is executed . This allows for specific error handling strategies for different types of exceptions, enhancing robustness and resilience of programs. For example, a code segment may generate an ArithmeticException or an ArrayIndexOutOfBoundsException. By using multiple catch blocks, each exception can be caught and handled differently, like printing 'Division by zero' for ArithmeticException and 'Array index out of bound' for ArrayIndexOutOfBoundsException . Once a specific catch block is executed, the others are bypassed, and execution continues beyond the try-catch structure . This capability is crucial for nuanced exception handling, ensuring precise response to varied run-time errors.

Method overloading and overriding both allow different methods to be defined with the same name but differ in argument list (overloading) or inheritance hierarchy and runtime behavior (overriding). In method overloading, static binding is used, meaning method calls are resolved at compile time based on the method signature, allowing different methods to exist with different parameters within the same class or a class hierarchy . This can lead to poorer performance due to the increased overhead at compile time. Conversely, method overriding relies on dynamic binding, where the method call is resolved at runtime, allowing for polymorphic behavior in subclass methods . This gives better performance as it allows appropriate methods to be invoked depending on the object's actual type. Private and final methods cannot be overridden but can be overloaded, emphasizing the compile-time resolution for static and private methods compared to the runtime determination of dynamic type .

The 'try-catch-finally' construct in Java is designed to handle exceptions and ensure that resources are managed correctly . Resources such as file streams, network connections, or other system resources are often opened and subsequently closed within a program, requiring careful handling to prevent resource leaks. The 'finally' block provides a mechanism to execute crucial resource management code, such as freeing, closing, or cleaning up resources, regardless of whether an exception is thrown or caught in the try or catch blocks . This mandatory execution makes the 'finally' block especially significant, as it guarantees the release of resources, ensuring robustness and stability in Java applications by preventing potential deadlocks or resource contentions even when exceptions occur.

Checked exceptions are those that occur at compile time and must be handled either using a try-catch block or declared using the 'throws' clause in the method signature . They are subclasses of Exception other than RuntimeException . Unchecked exceptions, on the other hand, occur at runtime and do not need to be caught or declared during compilation; they are subclasses of RuntimeException . This distinction implies that developers need to write explicit error handling code for checked exceptions to compile their programs, ensuring that potential errors are foreseen and managed at compile time. Unchecked exceptions allow more flexibility but require careful handling to prevent unexpected program crashes during execution.

Method overriding in Java allows a subclass to provide a specific implementation of a method already defined in its superclass. Dynamic binding is used in method overriding, which means that the method call is determined at runtime based on the object's actual type, allowing for polymorphic behavior . For example, consider the classes Animal, Dog, and Cat, where Dog and Cat override the sound method defined in Animal. The sound method in Dog prints 'Dog barks' and in Cat prints 'Cat meows' . If an Animal type reference is assigned to a Dog object, calling sound() will print 'Dog barks', demonstrating how Java dynamically binds the method call to the correct method implementation at runtime, supporting the seamless execution of overridden methods based on object types .

The 'throw' keyword in Java is used to explicitly raise an exception, effectively altering the normal execution flow of a program . When 'throw' is executed, it pauses the current flow and transfers control to the nearest enclosing try block followed by catch blocks that can handle the specified exception type . This immediate pause in execution allows developers to deliberately trigger an error event within a program's logic, such as when specific conditions are met, thus providing control over error management and the ability to execute alternative logic pathways . The use of 'throw' has significant implications for program flow, as it allows proactive error detection and handling based on custom scenarios or conditions, offering a way to manage and respond to unexpected states or inputs without relying solely on system-generated exceptions.

Static binding in Java is associated with method overloading, where the method call is resolved at compile time based on the method signature's parameter types and numbers . This means the exact method to invoke is determined when the program is compiled, leading to faster execution but potentially less flexible method selection. For example, multiple 'add' methods can exist in a class with different parameter lists, and static binding determines which method to call at compile time . In contrast, dynamic binding is related to method overriding, where the method call is determined at runtime based on the actual object's type—not the reference type . This enables polymorphism, allowing the program to decide which overridden method to execute based on the current object's runtime type, resulting in more flexible and adaptable code. Dynamic binding is essential in scenarios where different subclass objects are accessed through a superclass reference, providing runtime flexibility and enhancing method specificity based on object types.

You might also like