Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views42 pages

Module 4

Module 4 covers Exception Handling in Java, detailing the nature of exceptions, their hierarchy, and methods for handling them, including try-catch blocks and the use of finally. It distinguishes between checked and unchecked exceptions, provides examples of common exceptions, and explains the use of the throw and throws keywords. The module also discusses the importance of proper exception handling to maintain program flow and prevent crashes.

Uploaded by

gondelathanuz
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)
6 views42 pages

Module 4

Module 4 covers Exception Handling in Java, detailing the nature of exceptions, their hierarchy, and methods for handling them, including try-catch blocks and the use of finally. It distinguishes between checked and unchecked exceptions, provides examples of common exceptions, and explains the use of the throw and throws keywords. The module also discusses the importance of proper exception handling to maintain program flow and prevent crashes.

Uploaded by

gondelathanuz
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
You are on page 1/ 42

Module 4

Exception Handling

Dr. K.Aravind
Assistant Professor - SCOPE
VIT-AP University, Amaravati
Topics
• Exceptions
• Exception Hierarchy
• Throwing and Catching Exceptions
• Multiple Catch Clause-Nested Try statement
• throw-throws-finally
• Built in exceptions
• User Defined Exceptions.
Exception
• An exception is an abnormal event occurs during the execution of the
program, that interrupts the normal flow of the program‘s instruction.

• Exceptions are generated when a recognize the condition (usually an


error condition) during the execution of a method.

• Exception can be generated by Java-runtime system or they can be


manually generated by code.
Exception handling
• The ability of a program to intercept run-time errors, take corrective measures and
continue execution to maintain the normal flow of the application.

• An exceptions occur at various situations:


 Attempting to access a file that does not exist
 Inserting an element into an array at a position that is not in its bounds
 Performing some mathematical operation that is not permitted
 Declaring an array using negative values
 Resource allocation Error
 Problems in Network connectivity
Exception Hierarchy
Exceptions Types

1) Compile time exceptions 2) Run time exceptions


 Compiler time error means Java compiler
identify the syntax error at the time of Program may compile successfully several times and
compilation. compiler creates the class file of the program.
Compiler does not create .class file without But when the time of running the program, it shows the
successful compilation.
error is called run time error.
 Missing braces
 Missing semicolon The common problems are:
 Missing double quote in string  Divide by zero
 = instead of == operator, and etc .  Conversion of invalid string to number
 access the element that is out of bound of an array
 Passing the parameters with invalid range.
Checked Exception
• This exception is checked (notified) by the compiler at compilation-time
(compile time exceptions). These exceptions cannot simply be ignored, the
programmer should handle these exceptions
• Example: User writes FileReader class in the program to read data from a file. If
the file doesn't exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception
import java.io.File;
import java.io.FileReader;
public class Main
{
public static void main (String args[])
{
File file = new File ("file.txt");
FileReader fr = new FileReader (file);
}
}
Unchecked Exception
• This exception occurs at the time of execution called as Runtime Exceptions
such as logic errors or improper use of an API.
• Runtime exceptions are ignored at the time of compilation.
• Example: If user declared an array of size 3, and trying to call the 4th
element of the array then an ArrayIndexOutOfBoundsException exception
occurs.
public class Main{
public static void main (String args[])
{
int num[] = { 1, 2, 3 };
System.out.println (num[4]);
}}
Example - StringIndexoutofbounds
public class Main {
public static void main (String[]args) {
String s = "Welcome to the Classroom";
System.out.println ("String Length is : " + s.length ());
for (int j = 0; j < s.length (); j++) {
System.out.print (" " + s.charAt (j));
}
System.out.println ("Access the 50th alphabet:" + s.charAt (50));
}}
Example - IllegalArgumentException
public class Main {
static int v = 10;
public static int getValue (String s) {
if (s == null) {
throw new IllegalArgumentException ("Arguments can not be null");
}
return v;
}
public static void main (String[]args) {
String s = null;
try
{
System.out.println (getValue (s));
} catch (IllegalArgumentException e)
{
System.out.println (" IllegalArgumentException Caught");
}}}
Example – NullPointerException
//Example 1
public class Main {
public static void main(String[] args) {
Object ref = null;
ref.toString(); // throw a NullPointerException
}
}

//Example 2
class Sample {
public static Sample set_Value() {
return null; //returns a null object
} public void print(String s) {
System.out.println(s);
}
}
class Main{
public static void main(String[] args) {
Sample x = Sample.set_Value(); //create a new object (null object)
x.print("Hi!"); //invoke method using null object
}}
Errors
 Error is not considered as an Exception.
 Errors are problems that arise beyond the control of the programmer.
 Occurs due to the lack of system resources and our application should not
catch these types of problem.
 Errors mostly occur at runtime. So, they belong to an unchecked type.
 Ex : Stack Overflow Error, OutofMemory Error, System Crash Error. It is
irrecoverable. Errors are also ignored by the compiler.
public class Main{
public static void main (String[]args) {
recursiveMethod (10);
}
public static void recursiveMethod (int i) {
while (i != 0)
{ Error:
i = i + 1; java.lang.StackOverflowError
recursiveMethod (i);
}
}
}
Exception Handling
Different approaches to handle exceptions in Java
• try...catch block
• finally block
• throw and throws keyword

 try...catch block
 The try statement allows to define a block of try {
code to be tested for errors while it is being // Block of code to be tested
executed. }
catch(Exception e) {
 The catch statement allows to define a block of // Block of code to handle errors
code to be executed, if an error occurs in the try }
block
try .. catch
• If user declared an array of size 3, and trying to call the 4th element of the
array then an ArrayIndexOutOfBoundsException exception occurs.
public class Uncheck_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3};
System.out.println(num[4]);
} }

public class Uncheck_Demo {


public static void main(String[ ] args) {
try {
int[] num = {1, 2, 3};
System.out.println(num[4]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
try…catch block
public class Main {
public static void main(String ar[]){
try {
int x = 30 / 0;
} catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
}
}
Multiple Catch Block
 A single block of code can raise more than one exception.
 So, use two or more catch clauses for catching a different type of exceptions.
 At a time, only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e., catch for
ArithmeticException must come before catch for Exception.
 When using multiple catch statements, it is important to
remember that subclasses exception must come before any of
their superclass’s exception.
try{
//block of statements
 Because a catch statement that uses a superclass will catch }catch(Exception handler class
exceptions of that type as well as exceptions of its subclasses. subclass ){
} catch(Exception handler super
 Thus, a subclass exception would never be reached if it came class){
after its superclass that manifests as an unreachable code error. }
Multiple Catch Block
Multiple Catch Block
public class Main {
public static void main(String ar[]){
try{
int len = ar.length;
System.out.println(34/len); //bring it down for arrayindexerror
System.out.println(ar[5]);
}
catch(ArithmeticException e){
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("array index error");
}
} }
• catch blocks to be in order from specific to general catch block
class Arith{
int array[]={5,10,15,20}; catch(ArithmeticException e){
int num1 = 100; //catch ArithmeticException here.
int num2 =20; System.out.println(e);
public void multiCatch(){ }catch(Exception e){
try{ //catch general exceptions here.
//java.lang.ArithmeticException here if num2 = 0. System.out.println(e);
System.out.println(num1/num2); }
System.out.println("4th element of given System.out.println("Remaining code after
array = " + array[3]); exception handling.");
}
//ArrayIndexOutOfBoundsException here. }
System.out.println("5th element of given public class Main{
array = " + array[4]); public static void main(String args[]){
}catch(ArrayIndexOutOfBoundsException e){ Arith obj = new Arith();
System.out.println(e); obj.multiCatch();
} }
}
• catch blocks NOT in order from specific to general catch block
class Arith{ catch(ArrayIndexOutOfBoundsException e){
int array[]={5,10,15,20}; //Compile time error here.
int num1 = 100; System.out.println(e);
int num2 =20; }catch(ArithmeticException e){
public void multiCatch(){ //catch ArithmeticException here.
try{ System.out.println(e);
//java.lang.ArithmeticException here if num2 = 0. }
System.out.println(num1/num2); System.out.println("Remaining code after
System.out.println("4th element of given array = " exception handling.");
+ array[3]); }
//ArrayIndexOutOfBoundsException here. }
System.out.println("5th element of given array = " public class Main {
+ array[4]); public static void main(String args[]){
}catch(Exception e){ Arith obj = new Arith();
//catch general exceptions here. obj.multiCatch();
System.out.println(e); }
} }
Nested try Statements
 The try statement can be nested.

 If an inner try statement does not have a


catch handler for a particular exception,
the outer block’s catch handler will handle
the exception.

 This continues until one of the catch


statement succeeds, or until all the nested
try statements are exhausted .

 If no catch statement matches, then the


Java runtime system will handle the
exception.
Nested try Statements
public class Main { }
public static void main (String args[]) { //catch block of inner try block 2
//outer try block catch (ArrayIndexOutOfBoundsException e) {
try { System.out.println (e);
//inner try block 1 }
try { System.out.println ("other statement");
System.out.println ("Divide by 0 "); }
int x = 20 / 0; //catch block of outer try block
} catch (Exception e) {
System.out.println ("handled the exception (outer
//catch block of inner try block 1 catch)");
catch (ArithmeticException e) { }
System.out.println (e); System.out.println ("normal flow..");
} }}
//inner try block 2
try
{
int y[] = new int[10];
//assigning the value out of array bounds
y[25] = 40;
Finally clause in java
 The finally block follows a try block or a catch block.
 A finally block of code always executes, irrespective
of occurrence of an Exception.
 A try block can have one or more catch block
associated with it, but only one finally block can be try{
associates with it. //block of statements
} catch(){
Why finally is needed? } finally{
• The finally keyword is used to execute code }
without consideration of the occurrence of an
exception or not.
• Eg: freeing the resources i.e., closing the file,
database connectivity, etc.,
public class Main
{
public static void main (String args[]) {
int x[] = new int[2];
try
{
System.out.println ("Access element five :" + x[5]);
} catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("Exception thrown :" + e);
} finally
{
x[0] = 15;
System.out.println ("First element value: " + x[0]);
System.out.println ("The finally statement is executed");
}
}
}
Throws Clause
 Whenever an exception occurs in a method, it needs to handle by wrapping
the code that caused exception within the try-catch block or, throw/postpone
exception to the calling method using the throws keyword.
 Then, user need to handle the exception in the calling method.
 Use the throws keyword in the method declaration to declare the type of
exceptions that might occur within method, and it may throw by using the
throws keyword
 A throws clause specifies a list of exception types that a method might throw:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … {
// code
}

This example uses throws to declare multiple exceptions


Throws keyword
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
class A {
public static void findFile () throws IOException {
File newFile = new File ("C:\\Users\\rohit\\Desktop\\new\\Test.txt");
FileInputStream s = new FileInputStream (newFile);
System.out.println ("File size in bytes:" + newFile.length ());
// Reads the first byte
int i = s.read ();
while (i != -1) {
System.out.print ((char) i);
// Reads next byte from the file
i = s.read ();
}
s.close ();
}
public static void main (String[]args) {
try
{
findFile ();
} catch (IOException e)
{
System.out.println (e);
}
}
}
Throws keyword
While run this program, if the file test.txt does not exist, FileInputStream throws a
FileNotFoundException which extends the IOException class.
If a method does not handle exceptions, the type of exceptions that may occur within
it must be specified in the throws clause.
So, that methods further up in the call stack can handle them or specify them using
throws keyword themselves.
E.g.,:
 The findFile() method specifies that an IOException can be thrown.
 The main() method calls this method and handles the exception if it is thrown
Overriding Method With Throws
 The overriding method must NOT throw checked exceptions that are new or broader
than those declared by the overridden method.
 E.g.:
• A method that declares(throws) an SQLException cannot be overridden by a method that declares
an IOException, Exception or any other exception unless it is a subclass of SQLException.
• In other words, if a method declares to throw a given exception, the overriding method in a
subclass can only declare to throw the same exception or its subclass
• This rule does not apply for unchecked exceptions.
Overriding Method With Throws
class Base{
static void method() throws FileNotFoundException{
FileInputStream obj=new FileInputStream("a.txt");
class Base{
}}
static void method() throws ArithmeticException{
class Derived extends Base{
int x=10/0;
static void method() throws IOException{
}}
FileInputStream obj=new FileInputStream("b.txt"); } }
class Derived extends Base{
This will throw a compile time error!!! static void method() throws RuntimeException{
int x= Integer.parseInt("23.34");
class Base{ }
static void method() throws IOException { }
FileInputStream obj=new FileInputStream("a.txt");
} // This will throw a compile time error!!! Arithmetic
} Exception is Child to the Runtime Exception.
class Derived extends Base{
static void method() throws FileNotFoundException{
FileInputStream obj=new FileInputStream("b.txt");
}
}
Throw Clause
• System-generated exceptions are thrown automatically
• If user wants to throw the single exception explicitly at a time from a method or block of
code, apply the throw keyword. The exception-handler is also in the same block

Syntax:
throw new exception_class("error message");
Example:
throw new IOException("sorry device error")

public class A {
public static void main(String args[]) {
int age = 17;
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
else { System.out.println("Eligible to vote"); } } }
public class Main public class Main
{ {
public static void main (String args[]) public static void main (String args[])
{ {
int age = 17; try
if (age < 18) {
{ int age = 17;
throw new ArithmeticException ("Not eligible to if (age < 18)
vote"); throw new ArithmeticException ();
} }
else catch (ArithmeticException e)
{ {
System.out.println ("Eligible to vote"); System.out.println ("age is less than 18");
} }
} }
} }
Throw Clause for Checked and unchecked
Exception
//Checked
//import java.io.IOException;
//Unchecked
class Main { class Main
public static void getFile() throws IOException { {
// If user wants message “This file does not exist.” public static void outOfBounds ()
throw new IOException("This file does not exist."); {
} throw new StringIndexOutOfBoundsException ("This index
value is invalid.");
public static void main(String[] args) { }
try { public static void main (String[]args)
getFile(); {
} catch (IOException e) { outOfBounds ();
System.out.println(e.getMessage()); }
} }
}
}
Difference

throw throws

Used to throw an exception for a method or block Used to indicate what exception type may be
of code. thrown by a method

Cannot throw multiple exceptions Can declare multiple exceptions

Syntax: Syntax:
•throw is followed by an object (new type) •throws is followed by a class
•used inside the method •used with the method signature
User Defined Exceptions
• In java, user can define application specific user defined exceptions.
Ex:
• Creating an application for handling the voters database, the age
should be greater than or equal to 18.
• In this case, create a user defined exception which will be thrown
in case the age entered is less than 18.

While creating user defined exceptions, the following aspects to be considered:


 The user defined exception class should extend from the Exception class and its subclass.
 If user wants to display meaningful information about the exception, should override the
toString() method
User Defined Exceptions: Example 1
class CheckAge extends Exception public class Main
{ {
public CheckAge () public static void main (String args[])
{ {
System.out.println ("user defined exception"); try {
} int age = -12;
public String toString () if (age < 0)
{ throw new CheckAge ();
return "age is invalid"; }
} catch (CheckAge e) {
} System.out.println (e);
}
}
}
User Defined Exceptions: Example 2
// Custom exception class
class InvalidUsername extends Exception {
//constructor
public InvalidUsername (String message) { public static void main(String[] args) {
super(message); String username = "user123";
} try {
} validateUsername(username);
// Class that uses the custom exception System.out.println("Username is valid: " + username);
class Main { } catch (InvalidUsername e) {
public static void validateUsername(String username) throws System.out.println("Error: " + e.getMessage());
InvalidUsername { }
if (username.length() < 5) { }
throw new InvalidUsername("Username must be at least 5 }
characters long");
}
if (!username.matches("[a-zA-Z0-9_]+")) {
throw new InvalidUsername("Username can only contain
letters, digits, and underscores");
}
}
Java Built-in Exceptions
Java Built-in Exceptions
Java Built-in Exceptions
Problem
 Suppose you are developing an online shopping application where users can purchase
various items. As part of the checkout process, users are required to enter their credit
card information. Your application needs to handle exceptions that may arise during
the payment process.

 Consider scenarios such as network errors during payment processing, invalid credit
card information entered by the user, and insufficient funds in the user's account.

 How would you handle each of these scenarios gracefully, providing appropriate
feedback to the user while maintaining the security of their sensitive information?
import java.util.Scanner; class PaymentException extends Exception {
class PaymentProcessor { public PaymentException(String message) {
// Method to process payment super(message);
public void processPayment(String creditCardNumber, }}
double amount) throws PaymentException {
// Simulating network error
if (Math.random() < 0.2) { public class Main {
throw new PaymentException("Network error: public static void main(String[] args) {
Unable to process payment. Please try again later."); Scanner scanner = new Scanner(System.in);
} PaymentProcessor paymentProcessor = new
// Simulating invalid credit card number PaymentProcessor();
if (!isValidCreditCardNumber(creditCardNumber)) {
throw new PaymentException("Invalid credit card
// Get credit card information and amount from
number."); } user
// Simulating insufficient funds System.out.print("Enter credit card number: ");
if (amount > 1000.0) { String creditCardNumber = scanner.next();
throw new PaymentException("Insufficient funds: System.out.print("Enter payment amount: Rs.");
Your account balance is too low to complete the double amount = scanner.nextDouble();
transaction."); }
// If all checks pass, process payment
try {
System.out.println("Payment successful: Rs." + // Attempt to process payment
amount + " charged to credit card ending in " +
paymentProcessor.processPayment(creditCardNumber,
creditCardNumber.substring(creditCardNumber.length() - 4)); amount);
} } catch (PaymentException e) {
// Method to validate credit card number (simplified for
demonstration)
// Handle payment exceptions
private boolean isValidCreditCardNumber(String System.out.println("Payment failed: " +
creditCardNumber) { e.getMessage());
// Simplified validation: Check if credit card } finally {
number is not null and has 16 digits // Close scanner to prevent resource leak
return creditCardNumber != null && scanner.close(); } }}
creditCardNumber.length() == 16;
}}
End of Module 4

You might also like