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

1 Exception Handling(Unit 2)

The document provides an overview of exception handling in Java, explaining the types of exceptions (checked, unchecked, and errors) and the mechanisms for handling them using try, catch, throw, throws, and finally statements. It also discusses the importance of maintaining the normal flow of the application and includes examples of both inbuilt and user-defined exceptions. Additionally, it outlines the differences between 'throw' and 'throws' keywords and illustrates how to create custom exceptions.

Uploaded by

Mridula Verma
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)
8 views

1 Exception Handling(Unit 2)

The document provides an overview of exception handling in Java, explaining the types of exceptions (checked, unchecked, and errors) and the mechanisms for handling them using try, catch, throw, throws, and finally statements. It also discusses the importance of maintaining the normal flow of the application and includes examples of both inbuilt and user-defined exceptions. Additionally, it outlines the differences between 'throw' and 'throws' keywords and illustrates how to create custom exceptions.

Uploaded by

Mridula Verma
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/ 27

Exception Handling

Exception Handling
Exception: An unexpected event that disrupts the normal flow of the program.
It is an object which is thrown at runtime. Java provides:
1.Inbuilt (Predefined) Exceptions 2. User-Defined (Custom) Exceptions
Exception handling: Mechanism to handle runtime errors so that normal flow of
application can be maintained.
Core advantage: to maintain the normal flow of the application.

Types of Exception: checked and unchecked exception where error is considered as


unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception 2. Unchecked Exception 3. Error
Checked and Unchecked exceptions and Error
1) Checked Exception: The classes that extend Throwable class . Such exceptions
are checked at compile-time. e.g. IOException, SQLException etc.

2) Unchecked Exception: The classes that extend RuntimeException.


e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Not checked at compile-time rather they are checked at runtime.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionErroretc.
Hierarchy of Exception classes
Checked
and
UnChecked
Exceptions
Exception handling can be done by using these 5 statements:

1. Try 2. Catch 3. Throw 4. Throws 5. Finally


Keyword Use
try Wrap code that might throw an exception
catch Handle the exception
finally Always runs (cleanup or closing tasks)
throw Manually throw an exception
throws Declare that a method may throw an exception
Control Flow in Exceptions
Control Flow means how Java moves from one line to another when an exception occurs.
Control Flow With Exception (With Try-Catch)
Normal Control Flow (No Exception)
public class Example {
public class Example { public static void main(String[] args) {
public static void main(String[] args) { System.out.println("A");
System.out.println("A"); try {
System.out.println("B"); int a = 10 / 0; // Exception occurs here
System.out.println("C"); System.out.println("B"); // Skipped!
} } catch (ArithmeticException e) {
} System.out.println("C"); }
Output: System.out.println("D"); } }

A Output:
A
B C
C D Cont….
Flow Chart
JVM reaction to Exceptions

JVM Flow:

• JVM starts running our program


line by line.
• If it finds an error during
execution (like divide by 0, file
not found, etc.), it:Creates an
Exception object, Looks for a
matching catch block
Scenario JVM Reaction
Exception handled with try JVM catches it, runs catch block
Exception NOT handled JVM prints error + stack trace
Uncaught exception JVM terminates the program
try block
• used to enclose the code that might throw an exception.
• try block must be followed by either catch or finally block.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that runs no matter what (optional)
}

catch block
- used to handle the Exception.
- It must be used after the try block only.
- can use multiple catch block with a single try.
Problem without exception handling

public class Testtrycatch1{ Output:


public static void main(String args[]) Exception in thread main
java.lang.ArithmeticException:/ by
{ zero
int data=50/0; //throw exception
System.out.println("rest of the code...");
}}
• Program is interrupted in between. Though S.o.p. was correct but not get executed.

• There can be 100 lines of code after exception. So all the code after exception will
not be executed.
Solution by exception handling
Using try-catch block:

public class Testtrycatch Output:


Exception in thread main
{
java.lang.ArithmeticException:/ by zero
public static void main(String args[]){
try{ rest of the code...
int data=50/0;
}
catch(ArithmeticException e)
{ In this example, remaining part of the code is
executed i.e. rest of the code... statement is
System.out.println(e); printed.
}
System.out.println("rest of the code...");
}}
Multi catch block
To perform different tasks at the occurrence of different Exceptions, multi catch block is used.

public class TestMultipleCatchBlock {


public static void main(String args[]) {
try {
Ex:
int a[]=new int[5];
//a[5]=30/0;
a[5]=30/2;
}
catch(ArithmeticException e)
{System.out.println("Divide by Zero, task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Array index out of boundary, task 2 completed"); }
catch(Exception e)
{System.out.println("common task completed"); }
System.out.println("rest of the code...");
}}
nested try
Example
class ExcepNTRY {
public static void main(String args[]) {
try {
try{
System.out.println("going to divide");
int b =39/0;
} catch(ArithmeticException e) {System.out.println(e); }

try{
int a[]=new int[5];
a[5]=4;
} catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);}
System.out.println("other statement”);
} catch(Exception e){System.out.println("handeled");} System.out.println("normal flow..");
} }
finally block
• used to execute important code such as closing connection, stream etc.
• always executed whether exception is handled or not.
• follows try or catch block.

class TestFinallyBlock{
Ex: public static void main(String args[]){
try {
//int data=25/5; //run these 2 lines one at a time to check finally
int data=25/0;
System.out.println(data); }
catch(ArithmeticException e)
{ System.out.println(e); }
finally
{ System.out.println("finally block is always executed"); }
System.out.println("rest of the code...");
}
}
throw keyword
• used to explicitly/manually throw an exception. Can throw either checked or unchecked
exception. It is mainly used to throw custom exception.

Ex 1: create 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.

public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote"); }
public static void main(String args[])
{
validate(13);
//validate(19);
System.out.println("rest of the code..."); }
}
Ex 2: Throw

import java.util.Scanner;
class TestThrow2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter your roll number");
int roll = s.nextInt();

try {
if (roll < 0) {
throw new ArithmeticException("The number entered is not positive");
} else {
System.out.println("Valid roll number");
}
} catch (ArithmeticException e) {
System.out.println("An exception is thrown");
System.out.println(e.getMessage());
} }}
throws keyword
- used to declare an exception.
- gives an information to the programmer that there may occur an exception, thus, provide
the exception handling code so that normal flow can be maintained.

Syntax :

return_type method_name() throws exception_class_name{

//method code

}
Example throws Keyword
Here, we have a method that can throw Arithmetic exception so we mentioned that with the method
declaration and catch that using the catch handler in the main method.

public class Ex {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("You are not eligible to vote.");
} else {
System.out.println("You are eligible to vote.");
}
}

public static void main(String[] args) {


try {
checkAge(16);
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e.getMessage());
} } }
Difference between throw and throws

throw throws
used to declare an exception possible
used to throw an exception explicitly.
during its execution.
is followed by an instance of Throwable is followed by one or more Exception
class or one of its sub-classes. class names separated by commas.
is used with method signature (method
is declared inside a method body.
declaration).
We can declare multiple exceptions
We cannot throw multiple exceptions
(separated by commas) using throws
using throw keyword.
keyword.
Common Inbuilt (Predefined) Exceptions :

Exception Meaning

ArithmeticException Math errors (e.g., divide by 0)

NullPointerException Accessing something not initialized

ArrayIndexOutOfBoundsException Accessing array out of bounds

NumberFormatException Wrong string to number conversion


Example: Inbuilt Exception

public class InbuiltDemo {


public static void main(String[] args) { Output:
int a = 10;
int b = 0; Caught Exception:
java.lang.ArithmeticException:
try { / by zero
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e);
}
}
}
User- defined Exceptions
Apart from rich set of built-in Exceptions, JAVA provide the ability
to user to define Their Own Exception classes.

For example: if we want minimum amount to be filled before


starting a bank credit or debit transaction.

• All user defined Exceptions must be subclasses of Exception


class or its sub classes.

• To display meaningful information, user need to override the


toString() method.
Cont… User-Defined (Custom) Exceptions

Sometimes, we need to create our own exception class — to throw meaningful errors in
specific situations (like bank rules, school systems, voting, exams etc.)

Steps to Create a Custom Exception:


- Extend the Exception class (or RuntimeException)
- Create a constructor
- Use throw to trigger it

Example 1: To check the voter’s age

class AgeException extends Exception {


Step 1: Create the Custom Exception AgeException(String message) {
super(message);
}
}
Step 2: Use it in a Program

public class UserDefinedDemo {


static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18+ to vote."); Output:
} else {
System.out.println("Eligible to vote!"); Custom Exception
} Caught:
}
Age must be 18+
public static void main(String[] args) { to vote.
try {
checkAge(16);
} catch (AgeException e) {
System.out.println("Custom Exception Caught: " + e.getMessage());
} } }
Example 2:
import java.util.Scanner;
To check the
class UserDefinedExcepton extends Exception {
minimum OP:
public String toString() {
amount to
return "Wrong Amount Entered"; Enter amount to withdraw
withdraw: 12
} }
public class DEMO12 { Exception in thread "main" Wrong Amount
public static void main(String arg[]) throws Entered at DEMO12.main(DEMO12.java:20)
UserDefinedExcepton {
System.out.println("Enter amount to withdraw");
Scanner scan = new Scanner(System.in);
int k = scan.nextInt();
if (k < 100) {
throw new UserDefinedExcepton();
} else {
System.out.println("Your account is debited Rs " + k);
}} }

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy