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

Module4 Java

Module 4 covers the fundamentals of exception handling in Java, including types of exceptions, the use of try-catch blocks, and the mechanisms for throwing and handling exceptions. It explains built-in exceptions (checked and unchecked), user-defined exceptions, and the importance of managing exceptions to prevent abnormal program termination. Additionally, it discusses nested try statements and the role of keywords such as throw, throws, and finally in exception handling.

Uploaded by

the.knicks.yash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module4 Java

Module 4 covers the fundamentals of exception handling in Java, including types of exceptions, the use of try-catch blocks, and the mechanisms for throwing and handling exceptions. It explains built-in exceptions (checked and unchecked), user-defined exceptions, and the importance of managing exceptions to prevent abnormal program termination. Additionally, it discusses nested try statements and the role of keywords such as throw, throws, and finally in exception handling.

Uploaded by

the.knicks.yash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

MODULE-4 EXCEPTION HANDLING

MODULE 4,chapter-2

 Exception handling fundamentals


 Exception types
EXCEPTIONS  uncaught exceptions
 using try and catch
 using multiple catch clauses
 nested try statements
 throw, throws, finally
 chained exceptions

Exception Handling

QP) What is a Java exception? Explain the exception handling mechanism with example.

 “Exception is a class responsible for abnormal termination of the program whenever run
time errors occurred in a program”.
 A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
 Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
language or the constraints of the Java execution environment. Manually generated exceptions
are typically used to report some error condition to the caller of a method.
 When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error. That method may choose to handle the exception
itself, or pass it on.
 Exceptions can be generated by the Java run-time system, or they can be manually generated
by your code.
 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.
EXCEPTION HANDLING MECHANISM:

 Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
 Briefly, here is how they work. Program statements that you want to monitor for
exceptions are contained within a try block. If an exception occurs within the try
block, it is thrown. Our code can catch this exception (using catch) and handle it in
some rational manner.
 System-generated exceptions are automatically thrown by the Java run-time
SJCIT 2024 1
MODULE-4 EXCEPTION HANDLING

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.

Try
{
//critical code
}
Catch(Exceptiontype1 e)
{
//handler for the Exceptiontype1
}
.....
Catch(ExceptiontypeN e)
{
//handler for the ExceptiontypeN
}
Finally
{
//code to execute immediately after try block
}

Exception Types:

Exceptions can be categorized into two ways:

1. Built-in Exceptions
 Checked Exception
SJCIT 2024 2
MODULE-4 EXCEPTION HANDLING

 Unchecked Exception
2. User-Defined Exceptions

Built-in Exception

 Exceptions that are already available in Java libraries are referred to as built-in exception.
 It can be categorized into two broad categories, i.e., checked exceptions and unchecked
exception.

Checked exceptions

Checked exceptions are called compile-time exceptions because these exceptions are checked at
compile-time by the compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer should have to handle the exception; otherwise, the systemhas
shown a compilation error.

Example:
Sl.No
Exception Description
1 ClassNotFoundException Class not found.
2 CloneNotSupportedException Attempt to clone an object that does not implement
the Cloneable interface.
3 IllegalAccessException Access to a class is denied.
4 InstantiationException Attempt to create an object of an abstract class or
interface.
5 InterruptedException One thread has been interrupted by another thread.
6 NoSuchFieldException A requested field does not exist.
7 NoSuchMethodException A requested method does not exist.
8 FileNotFoundException A requested file does not exist.
Etc,,,.

Un-Checked 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.
 The unchecked exceptions defined in java.lang
Sl.No
Exception Description
1 ArithmeticException Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException Array index is out-of-bounds.
3 IndexOutOfBoundsException Some type of index is out-of-bounds.
4 NullPointerException Invalid use of a null reference.

SJCIT 2024 3
MODULE-4 EXCEPTION HANDLING

5 NumberFormatException Invalid conversion of a string to a numeric


format.
6 StringIndexOutOfBounds Attempt to index outside the bounds of a string.
7 ArrayStoreException Assignment to an array element of an
incompatible type.
8 ClassCastException Invalid cast.
9 EnumConstantNotPresentException Anattempt is made to use an undefined
enumeration value.
10 IllegalArgumentException Illegal argument used to invoke a method.
11 IllegalStateException Environment or application is in incorrect state.
12 IllegalThreadStateException Requested operation not compatible with current
thread state.
13 NegativeArraySizeException Array created with a negative size
14 SecurityException Attempt to violate security.
15 TypeNotPresentException Type not found

User Defined Exception


 In Java, we can write our own exception class by extends the Exception class. We can throw
our own exception on a particular condition using the throw keyword. For creating a user-
defined exception, we should have basic knowledge of the try-catch blockand
throw keyword.
 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.

Following are a few of the reasons to use custom exceptions:


 To catch and provide specific treatment to a subset of existing Java exceptions.
 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.

SJCIT 2024 4
MODULE-4 EXCEPTION HANDLING

Example:

// A Class that represents user-defined exception


package com.java;
class MyException extends Exception
{
public MyException( )
{
System.out.println(“My exception occurs”);
}
}

// A Class that uses above MyException


package com.java;
public class First
{
public static void main(String args[])// Driver Program
{
try
{ Output:
// Throw an object of user defined exception My exception occurs
throw new MyException( ) ;
}
catch (MyException ex)
{
System.out.println(ex);
}
}
}

SJCIT 2024 5
MODULE-4 EXCEPTION HANDLING

Using try, catch - Exception handling keywords


 Although the default exception handler provided by the Java run-time system is useful
for debugging, you will usually want to handle an exception yourself. Doing so provides
two benefits. First, it allows you to fix the error. Second, it prevents the program from
automatically terminating.
 To handle a run-time error, simply enclose the code that we want to monitor inside a try
block. Immediately following the try block, includes a catch clause that specifies the
exception type that you wish to catch.

Example:

import java.util.Scanner;

public class First


{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
try
{
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
Output 1: (Exception handled by using try and catch)

Output 2: (No Error)

SJCIT 2024 6
MODULE-4 EXCEPTION HANDLING

Qp)Create a try block that is likely to generate three types of exceptions and
incorporate necessary catch blocks to catch and handle them.
 To guard against and handle a run-time error, simply enclose the code that you want to
monitor inside a try block. Immediately following the try block, includes a catch clause
that specifies the exception type that you wish to catch.
 General working of try and catch block:
 Once an exception is thrown, program control transfers out of the try block into
the catch block.
 catch is not called, so execution never returns to the try block from a catch.
 Once the catch statement has executed, program control continues with the next
line in the program following the entire try/catch mechanism.
 A try and its catch statement form a unit. The scope of the catch clause is
restricted to those statements specified by the immediately preceding try
statement.
 A catch statement cannot catch an exception thrown by another try statement
(except in the case of nested try statements, described shortly).
 The statements that are protected by try must be surrounded by curly
braces. (That is, they must be within a block.) You cannot use try on a single
statement.
 The goal of most well-constructed catch clauses should be to resolve the
exceptional condition and then continue on as if the error had never happened.
 In some cases, more than one exception could be raised by a single piece of
code. To handle this type of situation, you can specify two or more catch clauses,
each catching a different type of exception.
 When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed.
 After one catch statement executes, the others are bypassed, and execution
continues after the try/catch block.
EXAMPLE:
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length; System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };

SJCIT 2024 7
MODULE-4 EXCEPTION HANDLING

c[42] = 99;
throw new IllegalAcessException;
}

catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}

Catch(IllegalAcessException e)
{
System.out.println("IllegalAcessException: " + e);
}
System.out.println("After try/catch blocks.");
}
}

Output:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

C:\>java MultiCatch TestArg


a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.

Uncaught Exceptions
 In java, assume that, if we do not handle the exceptions in a program. In this case,
when an exception occurs in a particular function, then Java prints an exception
message with the help of uncaught exception handler.
 The uncaught exceptions are the exceptions that are not caught by the compiler but
SJCIT 2024 8
MODULE-4 EXCEPTION HANDLING

automatically caught and handled by the Java built-in exception handler.


 Java programming language has a very strong exception handling mechanism. It
 allows us to handle the exception use the keywords like try, catch, finally, throw, and
throws.
 When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception
occurs and terminates the thread.
 The Division by zero exception is one of the example for uncaught
exceptions.Look at the following code.
import java.util.Scanner;

public class First


{

public static void main(String[] args)


{
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
}

Output:

In the above example code, we are not used try and catch blocks, but when the value of b is
zerothe division by zero exception occurs and it caught by the default exception handler.
Nested try statements
Nested try statements

 The try statement can be nested. That is, a try statement can be inside the block of another
try.
 Each time a try statement is entered, the context of that exception is pushed on the stack.
 If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound and the next try statement’s catch handlers are inspected for a
match. This continues until one of the catch statements succeeds, or until all of the
SJCIT 2024 9
MODULE-4 EXCEPTION HANDLING

nested try statements are exhausted. If no catch statement matches, then the Java run-
time system(JVM) will handle the exception.
 The inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).
 Let's consider the following example. Here the try block within nested try block (inner
try block 1) do not handle the exception. If it does not handle the exception, then the
control is transferred to the main try block (outer try block) where the appropriate catch
block handles the exception. It is termed as nesting.

Example:

import java.util.Scanner;
public class First
{
public static void main(String[] args)
{
int arr[]= {10,20,30};
Scanner sc= new Scanner(System.in);
System.out.println("Enter values of a and b");
int a=sc.nextInt();
int b=sc.nextInt();
try
{
int c=a/b;
System.out.println(c);
try
{
System.out.println(arr[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}

Qp)Write a note on:


SJCIT 2024 10
MODULE-4 EXCEPTION HANDLING

a) throw and throws


b) nested try statements
c) finally

a. throw:

 So far, we have only been catching exceptions that are thrown by the Java run-time system.
 However, it is possible for our program to throw an exception explicitly, using the throw
statement.
 The general form of throw is shown here:
throw ThrowableInstance; (or)
throw new exception_class( ) ; //we can pass parameter also

Where the throw Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend the
Exception class.
 The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.
 The nearest enclosing try block is inspected to see if it has a catch statement that matches
the type of exception.
 If it does find a match, control is transferred to that statement. If not, then the next
enclosing try statement is inspected, and so on.
 If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.

Example 1: Below program shows using throw keyword in User Defined Exception similarly
we can also use throw keyword in checked and unchecked Exceptions also.
class MyException extends Exception
{
public MyException( )
{
System.out.println(“My exception occurs”);
 } EXAMPLE 2:
} class ThrowDemo
{
// A Class that uses above MyException
static void demoproc()
public class First
{ {
// Driver Program try
public static void main(String args[]) {
{
try {
// Throw an object of user defined exception
throw new MyException( ) ;
SJCIT } 2024 11
catch (MyException ex)
{ System.out.println(ex);}
}
}
MODULE-4 EXCEPTION HANDLING

Example 2 class ThrowDemo


{
static void demoproc() {
`try
{
throw new NullPointerException("demo");
}

catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}

public static void main(String args[])


{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}

OUTPUT:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

b. throws:
 If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.
 You do this by including a throws clause in the method’s declaration. A throws clause
lists the types of exceptions that a method might throw.
 The Java throws keyword is used to declare an exception. It gives an information to
the programmer that there may occur an exception
SJCIT 2024 12
MODULE-4 EXCEPTION HANDLING

 general form:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Exception-list is a comma-separated list of the exceptions that a method can throw.
package jk ;

public class First


{
static void display ( int age ) throws ArithmeticException
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
System.out.println("Access granted - You are old enough!");
}
}

public static void main( String[ ] args )


{
display(15); // Set age to 15 (which is below 18...)
}
}

Output:

c. nested try statements:

 The try statement can be nested. That is, a try statement can be inside the block of
another try. Each time a try statement is entered, the context of that exception is pushed
on the stack.
 If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound and the next try statement’s catch handlers are inspected for a match.
 This continues until one of the catch statements succeeds, or until all of the nested try
SJCIT 2024 13
MODULE-4 EXCEPTION HANDLING

statements are exhausted.


 If no catch statement matches, then the Java run-time system will handle the exception
 EXAMPLE:

class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);

try
{
if(a==1)
a = a/(a-a); // division by zero
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}

This program nests one try block within another. The program works as follows.
SJCIT 2024 14
MODULE-4 EXCEPTION HANDLING

 When you execute the program with no command-line arguments, a divide-by-zero exception
is generated by the outer try block.
 Execution of the program with one command-line argument generates a divide-by-zero
exception from within the nested try block. Since the inner block does not catch this exception,
it is passed on to the outer try block, where it is handled.
 If you execute the program with two command-line arguments, an array boundary exception is
generated from within the inner try block.
OUTPUT:

C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One


a=1
Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestTry One Two


a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

d. finally:
o finally creates a block of code that will be executed after a try/catch block
has completed and before the code following the try/catch block.
o The finally block will execute whether or not an exception is thrown.
o If an exception is thrown, the finally block will execute even if no catch
statement matches the exception.
o The finally clause is optional. However, each try statement requires at least
one catch or afinally clause.
Syntax:

finally { //Statements; } // after try block

 finally creates a block of code that will be executed after a try/catch block has completed
and before the code following the try/catch block.
 Note: The finally block will execute whether or not an exception is thrown.
 If an exception is thrown, the finally block will execute even if no catch statement matches
the exception.
 Any time a method is about to return to the caller from inside a try/catch block, via an
SJCIT 2024 15
MODULE-4 EXCEPTION HANDLING

uncaught exception or an explicit return statement, the finally clause is also executed just
before the method returns.

 This can be useful for closing file handles and freeing up any other resources that might
have been allocated at the beginning of a method with the intent of disposing of them
before returning.
package jk;
import java.util.Scanner;

public class First


{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter values of a and b");
int a=sc.nextInt();
int b=sc.nextInt();
try
{
int c = a / b;
System.out.println( c );
}
catch(ArithmeticException e)
{
System.out.println( e );
}
finally
{
System.out.println("finally block executed if exception occure or not");
}
}
}

Output:

Chained Exceptions in Java

SJCIT 2024 16
MODULE-4 EXCEPTION HANDLING

 Chained Exceptions allows to relate one exception with another exception, i.e one exception
describes cause of another exception.
 For example, consider a situation in which a method throws an ArithmeticException because of
an attempt to divide by zero but the actual cause of exception was an I/O error which caused the
divisor to be zero.
 The method will throw only ArithmeticException to the caller. So the caller would not come to
know about the actual cause of exception. Chained Exception is used in such type of situations.
Constructors Of Throwable class Which support chained exceptions in java :

1. Throwable(Throwable cause) :- Where cause is the exception that causes the current exception.
2. Throwable(String msg, Throwable cause) :- Where msg is the exception message and cause is the
exception that causes the current exception.

Methods Of Throwable class Which support chained exceptions in java :


1. getCause() method :- This method returns the cause of the current Exception.
2. initCause(Throwable cause) method :- determines the reason for the calling Exception.

1. public class ChainedExceptionExample


2. {
public static void main(String[] args)
{
3. try
{
4. String s = null;
5. int num = Integer.parseInt(s); // the line will throw a NumberFormatException
6. }
7. catch (NumberFormatException e)
{
8. // create a new RuntimeException with the message "Exception."
9. RuntimeException ex = new RuntimeException("Exception");
// set the cause of the new Exception to a new NullPointerException with the message " It is a
ctual cause of the exception "
ex.initCause(new NullPointerException("It is actual cause of the exception"));
// throw the new Exception with the chained Exception
throw ex;
}
}
} SJCIT 2024 17
MODULE-4 EXCEPTION HANDLING

Output:

Exception in thread "main" java.lang.RuntimeException: Exception at


ChainedExceptionExample.main(ChainedExceptionExample.java:7)
Caused by: Java.lang.NullPointerException: It is actual cause of the
exception at ChainedExceptionExample.main(ChainedExceptionExample.java:8)

SJCIT 2024 18

You might also like