0% found this document useful (0 votes)
41 views12 pages

4 - Exception Handling in Java

1) Exceptions are problems that arise during program execution and disrupt normal flow. 2) There are three categories of exceptions: checked exceptions which must be handled, unchecked exceptions which occur at runtime, and errors which are irrecoverable. 3) Exception handling allows the program flow to continue after an exception rather than terminating abnormally.

Uploaded by

Ganesh
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)
41 views12 pages

4 - Exception Handling in Java

1) Exceptions are problems that arise during program execution and disrupt normal flow. 2) There are three categories of exceptions: checked exceptions which must be handled, unchecked exceptions which occur at runtime, and errors which are irrecoverable. 3) Exception handling allows the program flow to continue after an exception rather than terminating abnormally.

Uploaded by

Ganesh
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/ 12

Exception Handling in Java

An exception (or exceptional event) is a problem that arises during the execution (Runtime) of
a program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.

An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.

 A user has entered an invalid data.


 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has
run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.

Based on these, we have three categories of Exceptions. You need to understand them to
know how exception handling works in Java.

1) Checked exceptions − A checked exception is an


exception that occurs at the compile time, these are also
called as compile time exceptions. These exceptions
cannot simply be ignored at the time of compilation, the
programmer should take care of (handle) these
exceptions. (Exception checked by Compiler i.e. compiler
forces programer to include these exceptions)

For example, if you use FileReader class in your program


to read data from a file, if the file specified in its constructor
doesn't exist, then a FileNotFoundException occurs, and
the compiler prompts the programmer to handle the
exception.

2) Unchecked exceptions − An unchecked exception is an


exception that occurs at the time of execution. These are also
called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions
are ignored at the time of compilation.(not checked by compiler
hence called as unchecked exceptions)

For example, if you have declared an array of size 5 in your


program, and trying to call the 6th element of the array then an
ArrayIndexOutOfBoundsExceptionexception occurs.

3) Errors − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError


etc. these are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of


the application. Exception normally disrupts the normal flow of the
application that is why we use exception handling. Let's take a scenario:

Suppose there is 10 statements in your program and there occurs an


exception at statement 5, rest of the code will not be executed i.e. statement
6 to 10 will not run. If we perform exception handling, rest of the statement
will be executed. That is why we use exception handling in java.

Hierarchy of Java Exception classes

1) Checked Exception

The classes that extend Throwable class except


RuntimeException and Error are known as checked
exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as


unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time
rather they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


Common scenarios where exceptions may occur

Java - Built-in Exceptions

1) Java defines several exception classes inside the standard package java.lang.
2) The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available.
3) Java defines several other types of exceptions that relate to its various class libraries.
Following is the list of Java Unchecked RuntimeException.
Sr.No. Exception & Description
list of Java Checked Exceptions Defined in java.lang. ArithmeticException
1
Sr.No. Exception & Description Arithmetic error, such as divide-by-zero.
ClassNotFoundException ArrayIndexOutOfBoundsException
1 2
Class not found. Array index is out-of-bounds.
CloneNotSupportedException ArrayStoreException
3
2 Attempt to clone an object that does not Assignment to an array element of an incompatible type.
implement the Cloneable interface. ClassCastException
4
IllegalAccessException Invalid cast.
3 IllegalArgumentException
Access to a class is denied. 5
InstantiationException Illegal argument used to invoke a method.
4 Attempt to create an object of an abstract class or IllegalMonitorStateException
interface. 6
Illegal monitor operation, such as waiting on an unlocked thread.
InterruptedException
5 One thread has been interrupted by another IllegalStateException
7
thread. Environment or application is in incorrect state.
NoSuchFieldException IllegalThreadStateException
6 8
A requested field does not exist. Requested operation not compatible with the current thread state.
NoSuchMethodException
7 IndexOutOfBoundsException
A requested method does not exist. 9
Some type of index is out-of-bounds.
NegativeArraySizeException
10
Array created with a negative size.
NullPointerException
11
Invalid use of a null reference.
NumberFormatException
12
Invalid conversion of a string to a numeric format.
SecurityException
13
Attempt to violate security.
StringIndexOutOfBounds
14
Attempt to index outside the bounds of a string.
UnsupportedOperationException
15
An unsupported operation was encountered.
Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

1. try
2. catch
3. finally
4. throw
5. throws

1) Java try block

Java try block is used to enclose the


code that might throw an exception. It
must be used within the method.

Java try block must be followed by


either catch or finally block.

2) Java catch block

 Java catch block is used to handle the Exception. It must be used after the try block
only.
 If the type of exception that occurred is listed in a catch block, the exception is passed
to the catch block. Much as an argument is passed into a method parameter and catch
block executed.
 You can use multiple catch block with a single try.

Problem without exception handling

 Let's try to understand the problem if we don't use try-


catch block.
 As displayed in the right side example, rest of the
code is not executed (in such case, rest of the code...
statement is not printed).
 There can be 100 lines of code after exception.
So all the code after exception will not be
executed.

Solution by exception handling

Let's see the solution of above problem by java try-


catch block.

Now, as displayed in the above example, rest of the


code is executed i.e. rest of the code... statement is
printed.
Internal working of java try-catch block

The JVM firstly checks whether the


exception is handled or not. If exception
is not handled, JVM provides a default
exception handler that performs the
following tasks:

 Prints out exception description.


 Prints the stack trace (Hierarchy
of methods where the exception
occurred).
 Causes the program to terminate.

But if exception is handled by the


application programmer, normal flow of
the application is maintained i.e. rest of
the code is executed.

Java Multi catch block

If you have to perform different tasks


at the occurrence of different
Exceptions, use java multi catch
block.

Note: At a time only one Exception is


occurred and at a time only one catch
block is executed.

Note2: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException
must come before catch for Exception.
3) JAVA FINALLY BLOCK

 Java finally block is a block that is used to execute


important code such as closing connection, stream etc.
 Java finally block follows try or catch block.
 The finally block always executes when the try block
exits.

Note: If you don't handle exception, before terminating the


program, JVM executes finally block (if any).
Why use java finally

 Finally block in java can be used to put "cleanup" code


such as closing a file, closing connection etc.

Usage of Java finally

Here ur using NullPointerExp instead


of ArithmaticException or default
Exception e, hence exception is not
handled even using try catch block

rest of the code…. will not exucted

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 program


exits (either by calling System.exit() or by causing a
fatal error that causes the process to abort).

o/p
4) Java throw keyword

The Java throw keyword is used to explicitly throw an


exception.

We can throw either checked or unchecked exception in java


by throw keyword. The throw keyword is mainly used to
throw custom exception.

Java throw keyword example

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.

Java Exception propagation


An exception is first thrown from the top of the stack and if it is not caught, it drops down the
call stack to the previous method, If not caught there, the exception again drops down to the
previous method, and so on until they are caught or until they reach the very bottom of the call
stack. This is called exception propagation.

Rule1: By default Unchecked Exceptions are Rule2: By default, Checked Exceptions are not
forwarded in calling chain (propagated). forwarded in calling chain (propagated).
5) 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 normal flow 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 performing check up before the code being used.

Which exception should be declared?

Answer: checked exception only, because:

 unchecked Exception: under your control so correct your code.


 error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

 Now Checked Exception can be propagated (forwarded in call stack).


 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.
There are two cases:

1. Case1: You caught the exception i.e. handle the exception using try/catch.
2. Case2: You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception

 In case you handle the exception, the code will be


executed fine whether exception occurs during the
program or not.

Case2: You declare the exception

1) In case you declare the exception, if exception does not occur, the code will be
executed fine.
2) In case you declare the exception if exception occurs, an exception will be
thrown at runtime because throws does not handle the exception.

No. throw throws


1) Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception.
2) Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
You can declare multiple exceptions e.g.
5) You cannot throw multiple exceptions.
public void method()throws
No. final finally finalize
Final is used to apply restrictions on Finally is used to place important Finalize is used to perform clean
class, method and variable. Final code, it will be executed whether up processing just before object
1) class can't be inherited, final method exception is handled or not. is garbage collected.
can't be overridden and final variable
value can't be changed.
2) Final is a keyword. Finally is a block. Finalize is a method.
JAVA GARBAGE COLLECTION
 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime unused memory automatically.
In other words, it is a way to destroy the unused objects.
 To do so, we were using free() function in C language and delete() in C++. But, in java
it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection

 It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector (a part of JVM) so we don't need to
make extra efforts.

How can an object be unreferenced?

There are many ways:

1) By nulling the reference


2) By assigning a reference to another
3) By anonymous object etc.

finalize() method:

1) The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing.
2) This method is defined in Object class{java.lang.Object.finalize()} as :

3) This method is called by the garbage collector {System.gc()}when it determines no


more references to the object exist.(we can also override ths mthd as it there in lang pckg)

Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method
to perform cleanup processing (destroying remaining objects)
gc() method

The gc() method is used to invoke the garbage collector to perform


cleanup processing. The gc() is found in System and Runtime classes.

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC).


This thread calls the finalize() method before object is garbage collected.
EXCEPTIONHANDLING WITH METHODOVERRIDING IN JAVA
There are many rules if we talk about method overriding with exception handling. The Rules
are as follows:

1) If the superclass method does not declare an exception

If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but it can declare unchecked exception.

1) Rule: If the superclass method does not 2) Rule: If the superclass method does not
declare an exception, subclass overridden declare an exception, subclass overridden
method cannot declare the checked exception. method cannot declare the checked exception
but can declare unchecked exception.

2) If the superclass method declares an exception

If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.
Example in case subclass overridden method
Example in case subclass overridden method
declares same exception
declares parent exception

You might also like