Chapter 8
Chapter 8
Chapter-8
Excep on Handling
Java developers can handle exceptions to ensure the program does not terminate
abruptly. Users should receive a meaningful error message instead. For instance, when
writing a division program, if a user divides by zero, an exception is thrown due to the
undefined result. By handling this exception, we can prevent the program from crashing.
Example:
import java.util.Scanner;
public class MyProg {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the dividend: ");
int a = scanner.nextInt();
System.out.print("Enter the divisor: ");
int b = scanner.nextInt();
try {
int result = a / b;
Object Oriented Programming With JAVA
System.out.println("The result is: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}
Output:
In this example, if the user enters zero as the divisor, the program catches the
ArithmeticException and displays an error message instead of terminating unexpectedly.
Java's exception handling framework is built on the java.lang.Throwable class, which is the
root of the exception hierarchy. This class has two main subclasses: Exception and Error,
providing a structured approach to managing program errors.
1. Checked Exception
2. Unchecked Exception
3. Error
Understanding these categories is key for effective Java programming and ensuring that
your applications run smoothly.
1. Checked Exception: Checked exceptions in Java are exceptions that are verified at
compile-time. This means that if a method may throw a checked exception, it is required to
either handle it using a try-catch block or declare it using the throws keyword. Failing to do
so will result in a compilation error. Checked exceptions are classes that extend the
Throwable class, excluding RuntimeException and Error. Common examples of checked
exceptions include IOException and SQLException. Here are a few other checked exceptions.
Object Oriented Programming With JAVA
The method we previously employed is far from ideal for handling exceptions. It is
important to follow best practices in exception handling to ensure clarity and ease of
understanding. Each exception should be accompanied by a meaningful message, making it
easier for users to comprehend the error. Here's how the code should look for better exception
handling:
import java.io. *;
class MyProg {
public static void main(String args[])
{
FileInputStream s = null;
try{
s = new FileInputStream("MyProg.java");
} catch (FileNotFoundException e) {
System.out.println("file not found at the given location");
}
int k;
try {
while ((k = s.read() ) != -1)
{
System.out.print((char)k);
}
s.close();
} catch (IOException e) {
System.out.println("I/O exception occurred Error code: "+e);
}
}
}
Output:
Object Oriented Programming With JAVA
Output:
Object Oriented Programming With JAVA
Difference Between Checked and Unchecked Exception
3. Error vs exception
Conversely, exceptions are runtime events triggered by issues like incorrect user data
or flawed programming logic. These can be managed by the programmer, who can implement
corrective measures. Java's java.lang package contains numerous exception classes, with many
falling under the umbrella of RuntimeException. Since java.lang is automatically imported into
all Java programs, exceptions derived from RuntimeException are readily accessible to
developers. By effectively handling exceptions, programmers can enhance the robustness and
reliability of their Java applications.
try- In Java, a try block is used to encapsulate code that may potentially throw an
exception. By surrounding this code within a try block, you prepare for handling possible errors
that could disrupt the program’s flow. If an exception is thrown, it is caught by the appropriate
catch block. Remember, a try block must always be paired with either a catch block or a finally
block within a method to properly manage exceptions.
Syntax: try{
// Code that may cause an exception
}
catch- In programming, the catch block is designed to manage exceptions thrown by
the try block. To efficiently address various types of exceptions, you can utilize multiple catch
blocks.
Syntax: catch (Exception e)
{
// Handle the exception
}
Object Oriented Programming With JAVA
finally- In Java programming, the "finally" block is essential for executing code that
must run, regardless of whether an exception was thrown or caught. This block is primarily
used for resource cleanup, such as closing connections and streams. A key feature of the Java
"finally" block is that it always executes, regardless of how the preceding try or catch blocks
are handled. As such, it is crucial for ensuring the consistent release of resources in your Java
applications.
Syntax:
try {
// Code that may cause an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// (Optional) Block that always executes
}
Object Oriented Programming With JAVA
1. A finally block must be directly associated with a try block—you cannot have a finally
block without including a try block. It's ideal to place statements here that should always be
executed, regardless of what occurs in the try block.
2. While the finally block is optional, remember that a try-catch block is often sufficient
for handling exceptions. However, when included, a finally block will always run after the try
block completes.
3. Under normal circumstances, when no exceptions are thrown in the try block, the
finally block executes immediately afterwards. In the event of an exception, the catch block
executes first, followed by the finally block.
4. Exceptions that occur within the finally block behave just like any other exception,
potentially altering the program's flow.
5. The statements within a finally block execute even if the try block contains control
transfer statements like return, break, or continue.
The basic exception handling example as
public class MyProg{
public static void main (String [] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Output:
When an unhandled exception occurs, the program terminates and displays a system-
generated error message to the user. Unfortunately, these messages are often not user-
friendly, making it difficult for users to understand the problem. To address this, programmers
handle exceptions and display clear, user-friendly error messages instead. By doing so, users
can easily identify and rectify the issue, as exceptions usually stem from incorrect data entry.
Nested try catch block
In programming, when a try-catch block is placed within another try block, it is referred
to as a nested try-catch block. If an exception arises within the inner try block and there isn't
a corresponding catch handler, the outer try block's catch handlers are checked. If a match is
found, the relevant catch block executes to handle the exception. However, if neither the inner
Object Oriented Programming With JAVA
nor outer catch blocks can handle the exception, a system-generated error message is
displayed, similar to what happens when exceptions are not handled at all.
Syntax:
try {
statement 1;
statement 2;
try { //try-catch block inside another try block
statement 3;
statement 4;
try { //try-catch block inside nested try block
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}
}
catch(Exception e3) {//catch of Main(parent) try block
//Exception Message
}
Example:
class MyProg{
public static void main(String args[]){
//Parent try block
try{
try{//Child try block1
int b =30/0;
System.out.println("Inside block1"+b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
try{ //Child try block2
int b =49/0;
System.out.println(“Inside block2”+b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
Object Oriented Programming With JAVA
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException Inside parent try catch
block");
}
catch(Exception e5){
System.out.println("Exception Inside parent try catch block");
}
}
}
Output:
throw- The Java throw keyword is essential for explicitly throwing exceptions within
your code. Whether you need to throw a checked or unchecked exception, the throw keyword
allows for this flexibility. It's particularly useful for generating custom exceptions, enabling you
to throw user-defined or customized exception objects directly to the Java Virtual Machine
(JVM). This functionality makes it a crucial tool for developers aiming to enhance error handling
and create more robust Java applications.
Syntax: throw exception;
Example:
class MyProg {
static void checkEligible(int age) {
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) {
checkEligible(14);
}
}
Output:
Exception Handling is crucial for managing checked exceptions. However, for unchecked
exceptions like NullPointerException, programmers should conduct pre-execution checks to
prevent potential issues. By using the `throws` keyword, we ensure that any exceptions are
passed to the Java Virtual Machine (JVM) for further handling.
Syntax:
return_type method_name() throws exception_class_name{
//method code
}
Example:
import java.io.IOException;
class MyProg{
void disp()throws IOException{
throw new IOException("error in output");//checked exception
}
void input() throws IOException{
disp();
}
void print(){
try{
input() ;
}catch(Exception e){
System.out.println("exception handled manually");
}
}
public static void main(String []args){
MyProg obj=new MyProg();
obj.print();
System.out.println("program working normally");
}
}
Output:
Throw vs throws
Throw Throws
Java throw keyword is used to Java throws keyword is used to declare an
1
explicitly throw an exception. exception.
Checked exception cannot be Checked exception can be propagated
2
propagated using throw only. with throws.
Java allows creating user-defined exceptions. We can create our own exception by
extending exception class. The throw and throws keywords are used while implementing user
defined exceptions
Example:
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}
public class MyProg{
static void validateAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or above.");
} else {
System.out.println("Valid age.");
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (AgeException e) {
System.out.println(e.getMessage());
}
}
}
Output:
Final
final is a keyword used to apply restrictions on class, method and variables. final class can’t be
inherited, final method can’t be overridden and final variable value can’t be changed.
example
class MyProg{
public static void main(String[] args){
final int x=10;
x=20;//Compile Time Error will occurred
Object Oriented Programming With JAVA
}
}
Output:
finally
finally, is the part of try-catch block.it will be executed whether exception is handled or not.it
is optional part with try. It is a block of code used with try and catch.
example
class MyProg{
public static void main(String[] args){
try{
int x=50;
}catch(Exception e){
System.out.println(e);
}finally{
System.out.println("finally block is executed");
}
}
}
Output:
finalize
finalize is a method. finalize is used to perform cleanup processing just before object is
garbage collected.
example
class MyProg{
public void finalize(){
System.out.println("finalize method called");
}
public static void main(String[] args){
MyProg f1=new MyProg ();
MyProg f2=new MyProg ();
f1=null;
f2=null;
System.gc();
}
}
Output: