UNIT 3 Module1
UNIT 3 Module1
3.1. EXCEPTIONS
An exception is a problem that arises during the execution 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.
o A user has entered an invalid data.
o A file that needs to be opened cannot be found.
o A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Example:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Note: Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest
of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling,
the rest of the statement will be executed. That is why we use exception handling.
1
Regulation: IFETCER-2019 Academic Year: 2023-2024
Syntax
try{
// code
}
catch(Exception_type1){
// catch block1
}
catch(Exception_type2){
//catch block 2
}
finally{
//finally blockalways execute
}
Fig3.1.1 Exceptions
Example:
public class Main {
public static void main(String[] args)
{ try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
}
}
}
3.2 EXCEPTION HIERARCHY
All exception classes are subtypes of the [Link] class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is
derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java
programs. Errors are generated to indicate errors generated by the runtime environment. Example:
2
Regulation: IFETCER-2019 Academic Year: 2023-2024
Runtime Exception:
RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation
of the Java VM (Virtual Machine).
Example
public class TryCatchExample {
public static void main(String[] args) {
try {
int data=50/0; //may throw exception
3
Regulation: IFETCER-2019 Academic Year: 2023-2024
}
catch(ArithmeticException e){
[Link](e);
}
[Link]("rest of the code");
}
}
Output
[Link]: / by zero
rest of the code
4
Regulation: IFETCER-2019 Academic Year: 2023-2024
5
Regulation: IFETCER-2019 Academic Year: 2023-2024
is generally used to find the root cause of an error. If there are multiple causes for the error or exception, this
method returns the innermost cause.
Syntax:
public final Throwable getCause()
Example:
class GetCauseDemo {
public static void main(String args[])
{ try {
int a[] = new int[5];
a[-1] = 1;
} catch (Exception e){
Throwable t = new Throwable(" caused by access to invalid array length ",e);
8
Regulation: IFETCER-2019 Academic Year: 2023-2024
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 Runtime Exception. 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. This chapter will not be
dealing with exceptions of type Error, because these are typically created in response to catastrophic
failures that cannot usually be handled by your program
Exception Types:
Java defines several types of exceptions that relates to various class [Link] are two major types of
[Link] also allows the user to define their own exceptions.
9
Regulation: IFETCER-2019 Academic Year: 2023-2024
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
3.3.3 User defined Exception:
Here are some rules to create Exception class in User-defined Exception:
1. Constructor: This is not mandatory in creating any constructor in the custom exception class. Providing
parameterized constructors in the custom exception class is a good practice.
2. Naming Convention: All exception classes are provided by the JDK end; hence, a custom exception should
follow a naming convention.
3. Extends Exception class: If the user is creating a custom exception class, then the user has to extend the
Exception class.
Syntax:
class SampleException{
public static void main(String args[]){
try{
10
Regulation: IFETCER-2019 Academic Year: 2023-2024
throw new UserException(<value>); // used to create new exception and throw
11
Regulation: IFETCER-2019 Academic Year: 2023-2024
}
catch(Exception e){
[Link](e);
}
}
}
class UserException extends Exception{
// code for exception class
}
Example:
Class SampleException{
public static void main(String args[]){
try{
throw new UserException(400);
}
catch(UserException e){
[Link](e) ;
}
}
}
class UserException extends
Exception{ int num1;
UserException(int num2) {
num1=num2;
}
public String toString(){
return ("Status code = "+num1) ;
}
}
3.4. USING TRY AND CATCH
3.4.1. Try-block:
The code which might raise exception must be enclosed within try-block in the program.
The try-block must be followed by either catch-block or finally-block at the end of the program.
If both present, it is still valid but the sequence of the try-catch-finally block is the flow which is used
for most of the programs.
Otherwise, compile-time error will be thrown for invalid sequence.
The valid combination like try-catch block or try-catch-finally blocks must reside inside Main
Method.
Note: The code inside try-block must always be wrapped inside curly braces, even if it contains just
one line of code; Otherwise, compile-time error will be thrown inside the compiler.
3.4.2 Catch-block:
It contains handling code for any exception raised from corresponding try-block and it must be
enclosed within catch block
The catch-block takes one argument which should be of type Throwable or one of its sub-
classes i.e.; class-name followed by a variable
The variable contains exception information for exception raised from try-block.
Note: The code inside catch-block must always be wrapped inside curly braces, even if it contains
just one line of code; Otherwise, compile-time error will be thrown.
12
Regulation: IFETCER-2019 Academic Year: 2023-2024
Example:
class Exc2 {
public static void main(String args[]) {
int d, a;
try {
// monitor a block of code.
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
}
catch (ArithmeticException e) {
// catch divide-by-zero error
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
Once an exception is thrown, program control transfers out of the try block into the catch block. Put
differently, catch is not “called,” so execution never “returns” to the try block from a catch.
Thus, the line "This will not be printed." is not displayed. Once the catch statement has executed,
program control continues with the next line in the program following the entire try /catch
mechanism.
13
Regulation: IFETCER-2019 Academic Year: 2023-2024
Output
Arithmetic Exception occurs
rest of the code
Note: When you use multiple catch statements, it is important to remember that exception subclasses must
come before any of their super classes. This is because a catch statement that uses a superclass will catch
exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its
superclass. Further, in Java, unreachable code is an error.
For example, consider the following program:
class SuperSubCatch {
public static void main(String args[])
{ try {
14
Regulation: IFETCER-2019 Academic Year: 2023-2024
int a = 0;
int b = 42 / a;
}
catch(Exception e) {
[Link]("Generic Exception catch.");
}
catch(ArithmeticException e) {
// ERROR – unreachable
[Link]("This is never reached.");
}
}
}
Note:
If you try to compile this program, you will receive an error message stating that the second catch
statement is unreachable because the exception has already been caught.
Since Arithmetic Exception is a subclass of Exception, the first catch statement will handle all
Exception-based errors, including Arithmetic Exception.
This means that the second catch statement will never execute.
15
Regulation: IFETCER-2019 Academic Year: 2023-2024
Example:
// An example of nested try statements.
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("normal flow..");
}
}
Output
Going to divide by 0
[Link]: /by zero
[Link]: Index 5 out of bounds for length5
Other statement
Normal flow..
16
Regulation: IFETCER-2019 Academic Year: 2023-2024
Execution Flow In nested try-catch blocks, the inner In multiple catch blocks, only the
catch blocks are skipped if an first catch block that matches the
exception is caught in the outer exception type is executed.
block.
17
Regulation: IFETCER-2019 Academic Year: 2023-2024
Output:
Number is negative,cannot calculate square
at [Link]([Link])
at [Link]([Link])
3.8 THROWS CLAUSE:
The Java throws keyword is used to declare an exception. It gives 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.
Syntax
return_type method_name() throws exception_class_name{
//method code
}
Throws keyword is used to declare the exception that might raise during program execution
Whenever exception might thrown from program, then programmer doesn’t necessarily need to handle
that exception using try-catch block instead simply declare that exception using throws clause
next to method signature
But this forces or tells the caller method to handle that exception; but again caller can handle that
exception using try-catch block or re-declare those exception with throws clause
Note: use of throws clause doesn’t necessarily mean that program will terminate normally rather it is
the information to the caller to handle for normal termination
Any number of exceptions can be specified using throws clause, but they are all need to be
separated by commas (,)
throws clause is applicable for methods & constructor but strictly not applicable to classes
It is mainly used for checked exception, as unchecked exception by default propagated back to the
caller (i.e.; up in the runtime stack)
Example
import [Link];
class ExceptionHandling {
void method3() throws IOException {
throw new IOException("device error");// checked exception
}
void method2() throws IOException {
method3();
}
void method1()
{ try {
method2();
} catch (IOException exp)
{ [Link]("exception
handled");
}
}
public static void main(String args[])
{ ExceptionHandling obj = new
ExceptionHandling(); obj.method1();
[Link]("normal flow...");
}
}
Output
exception handled
18
Regulation: IFETCER-2019 Academic Year: 2023-2024
normal flow...
19
Regulation: IFETCER-2019 Academic Year: 2023-2024
3.9 FINALLY-BLOCK:
Java finally block is a block that is used to execute important code such as closing connection, stream
etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
Syntax:
try {
// code that may cause exceptions
} catch (ExceptionType ex) {
// exception handling code
} finally {
// code that will always be executed, whether an exception occurs or not
}
Example
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){
[Link](e);
}
finally{
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Output
finally block is always executed
rest of the code...
Important points regarding finally block:
A finally block must be associated with a try block, you cannot use finally without a try block.
You should place those statements in this block that must be executed always.
In normal case when there is no exception in try block then the finally block is executed after try
block. However if an exception occurs then the catch block is executed before finally block.
20
Regulation: IFETCER-2019 Academic Year: 2023-2024
An exception in the finally block, behaves exactly like any other exception.
The statements present in the finally block execute even if the try block contains control
transfer statements like return, break or continue.
Finally block when using return statement:
class JavaFinally
{
public static void main(String args[])
{
[Link]([Link]());
}
public static int myMethod()
{
try {
return 112;
}
finally {
[Link]("This is Finally block");
[Link]("Finally block ran even after return statement");
}
}
}
Output:
This is Finally block
Finally block ran even after return statement
112
3.10 BUILT-IN EXCEPTIONS
Java defines several exception classes inside the standard package [Link].
The most general of these exceptions are subclasses of the standard type RuntimeException. Since
[Link] is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.
Java defines several other types of exceptions that relate to its various class libraries.
Following is the list of Java Unchecked RuntimeException.
Built-in Exceptions
Basically, built-in Exceptions are those exceptions that are pre-defined in Java Libraries. These are
the most frequently occurring Exceptions.
An example of a built-in exception can be ArithmeticException, it is a pre-defined exception in the
Exception class of [Link] package. These can be further divided into 2 types:
Checked Exception
Unchecked Exception
21
Regulation: IFETCER-2019 Academic Year: 2023-2024
Unchecked Exception:
S.
Exception Description
No.
1 ArithmeticException Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException Array index is out-of-bounds.
3 ArrayStoreException Assignment to an array element of an incompatible
type.
4 ClassCastException Invalid cast.
5 IllegalArgumentException Illegal argument used to invoke a method.
6 IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
7 IllegalStateException Environment or application is in incorrect state.
8 IllegalThreadStateException Requested operation not compatible with the current
thread state.
9 IndexOutOfBoundsException Some type of index is out-of-bounds.
10 NegativeArraySizeException Array created with a negative size.
11 NullPointerException Invalid use of a null reference.
12 NumberFormatException Invalid conversion of a string to a numeric format.
13 SecurityException Attempt to violate security.
14 StringIndexOutOfBounds Attempt to index outside the bounds of a string.
15 UnsupportedOperationException An unsupported operation was encountered.
Example
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
[Link]([Link](0));
}
catch (NullPointerException e) {
[Link]("NullPointerException..");
22
Regulation: IFETCER-2019 Academic Year: 2023-2024
}
}
}
Output
NullPointerException..
23
Regulation: IFETCER-2019 Academic Year: 2023-2024
}
}
public static void main()
{
interruptException obj = new interruptException();
[Link]();
[Link]();
}
}
Output:
[Link]: sleep interrupted
3. SQL Exception:
SQLException is thrown if there is an error in database access or other database errors.
To access the Database, we use various functions like Connection, DriverManager, and getConnection.
If we want to access a database at some URL, now if that URL is not accessible to the code, then it will
throw the SQLException.
We will use throws to handle the SQLException.
Example:
public class sqlexception
{
public static void main() throws SQLException
{
Connection conn = [Link]("Database_URL");
}
}
Output:
[Link]: No suitable driver found for Database_URL
4. I/O Exception:
IOException is one of the most commonly handled exceptions.
It is thrown when there is some sort of discrepancy in Input or Output. Using throws suppresses it
and not using throws will give a compile-time error.
Example:
class Main {
public static void main(String[] args) {
try {
// Creating an instance of FileReader class
FileReader fileReader = new
FileReader("[Link]");
[Link]([Link]());
[Link]();
}
catch (IOException e) {
[Link](e);
}
}
}
Output:
[Link]: [Link] (No such file or directory)
25
Regulation: IFETCER-2019 Academic Year: 2023-2024
string as Null, and then try to access it, then JVM will throw the NullPointerException.
Output:
class nullpointerexception
{
public static void main()
{
String s = null;
[Link]([Link]());
}
}
Output:
[Link]
4. Array Index Out of Bounds Exception:
ArrayIndexOutOfBounds is one of the most common unchecked exceptions. It is thrown when we try to
access an array index that does not exist. Let us say that we have an array of size 10, and we try to access the
15th element. Then JVM will throw an ArrayIndexOutOfBounds exception.
Example:
class arrayindexoutofbounds
{
public static void main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
[Link](arr[15]);
}
}
Output:
[Link]: Index 15 out of bounds for length 10
3.11 CREATING OWN EXCEPTIONS
If you are creating your own Exception that is known as custom exception or user-defined exception.
Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
3.11.1 Why use custom exceptions?
Java exceptions cover almost all the general type of exceptions that may occur in the programming.
However, sometimes it is need to create custom exceptions.
Following are few of the reasons to use custom exceptions:
o To catch and provide specific treatment to a subset of existing Java exceptions.
o Business logic exceptions: These are the exceptions related to business logic and workflow. It
is useful for the application users or the developers to understand the exact problem.
In order to create custom exception, we need to extend Exception class that belongs to [Link]
package.
Example:
// [Link]
class InvalidAgeException extends
Exception{ InvalidAgeException(String s){
super(s);
}
}
// [Link]
class TestCustomException1{
27
Regulation: IFETCER-2019 Academic Year: 2023-2024
Example:
Class Examplethrows
{
Static void divide_m() throws ArithmeticException
{
Int x=22,y=0.z;
Z=x/y;
}
Public static void main(String args[])
{
Try
{
Divide_m();
}
Catch(Arithmetic Exception e)
{
[Link](“Caught the Exception”+e);
}
}
}
Output:
Caught the Exception [Link]: /by zero
28
Regulation: IFETCER-2019 Academic Year: 2023-2024
3.12.2 Activity:User defined exception for invalid age for voting system.
The User defined Exception has been described with another example called as age filtering for voting system
to allow only eligible voters.
Example:
Class InvalidAgeException extends
Exception{ InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}
catch(Exception m)
{ [Link]("Exception occured:
29
Regulation: IFETCER-2019 Academic Year: 2023-2024
"+m);
30
Regulation: IFETCER-2019 Academic Year: 2023-2024
}
[Link]("rest of the code...");
}
}
Output:
Output:Exception occured: InvalidAgeException:not valid
rest of the code...
31