KEMBAR78
OOP Lab 11 | PDF | Java (Programming Language) | Software
0% found this document useful (0 votes)
44 views8 pages

OOP Lab 11

Uploaded by

emanshaikh999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views8 pages

OOP Lab 11

Uploaded by

emanshaikh999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Department of Computer Science

Course Code: CSC103


Title: Object-Oriented Programming

Fall 2024

Lab 11
Objective:

Introduction to Exception Handling

Student Information

Student Name

Student ID

Date

Assessment

Marks Obtained

Remarks

Signature
LAB -11
Exception Handling
Objectives:

 Introduction to Exception Handling


 Need for Exception Handling
 Implementation of Exception Handling in Java
 Handling a TypeError-like Exception

Apparatus:
Hardware requirements:
Dual core CPU based on x64 architecture
Minimum of 1 GB RAM
800 MB of disk space
Software requirements:
Windows 7 SP1 (64 bit)
Java JDK 8 (64 bit JVM)
NetBeans IDE (version 8.1 or above)

Background:
Exception is an indication that something went wrong in the program execution and it can be recovered.
Error is a condition when something serious went wrong and it can’t be recovered.
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

What is Exception Handling?


When executing Java code, different errors can occur: coding errors made by the programmer, errors
due to wrong input, or other unforeseeable things. When an error occurs, Java will normally stop and
generate an error message. The technical term for this is: Java will throw an exception (throw an
error).Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception

.
3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes each.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle exceptions.

.
Exception Handling in Java
Java uses a try-catch block to handle exceptions. The try block contains the code that might throw an
exception, and the catch block catches and handles the exception.
Try and catch block
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block. The try and catch keywords come in pairs:

The try: block contains one or more statements which are likely to encounter an exception. If the
statements in this block are executed without an exception, the subsequent except: block is skipped.

If the exception does occur, the program flow is transferred to the except: block. The statements in
the except: block are meant to handle the cause of the exception appropriately. For example, returning
an appropriate error message

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle
the exception.

JavaExceptionExample.java

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program

.
System.out.println("rest of the code...");
}
}
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:

Exercise 1: Handling a TypeError-like Exception

Write a Java program that takes user input to catch a TypeError-like exception. Specifically, handle the
scenario where the user enters a non-integer value when the program expects an integer.
import java.util.Scanner;

public class TypeErrorHandlingExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter an integer: ");
int num = scanner.nextInt();

System.out.print("Enter another integer: ");


int anotherNum = scanner.nextInt();

int result = num + anotherNum;

.
System.out.println("Result: " + result);
} catch (java.util.InputMismatchException ex) {
System.out.println("Error: Invalid input. Please enter integers only.");
} finally {
scanner.close(); // Close the Scanner to prevent resource leaks
System.out.println("Finally block executed");
}
} // This is the missing closing brace for the main method

} // This is the missing closing brace for the class

Exercise 2: Raise an Exception


The throw keyword
The throw statement allows you to create a custom error. The throw statement is used together with
an exception type. There are many exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityExce
ption, etc:

Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access
granted":

In Java, you can explicitly throw an exception using the throw keyword. Below is an example of how to
raise a custom exception in Java: Modify the program to explicitly raise an exception if the second input
is not an integer.

.
// Exercise 2: Raise an Exception
import java.util.Scanner;

public class RaiseExceptionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter an integer: ");
int num = scanner.nextInt();

System.out.print("Enter another value: ");


String userInput = scanner.next();

if (!userInput.matches("\\d+")) {
throw new NumberFormatException("Invalid input. Please enter an integer.");
}

int anotherNum = Integer.parseInt(userInput);


int result = num + anotherNum;

System.out.println("Result: " + result);


} catch (NumberFormatException ex) {
System.out.println("Error: " + ex.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
}

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException
.
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs


If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into digit will cause
NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Exercises:

1. Write a Java program that takes user input for two integers and performs division. Handle the
InputMismatchException if the user enters a non-integer value. Use a try-catch block to handle the
exception and display an appropriate error message.

2. Write a Java program to calculate the average of an array of numbers. Create a custom exception
called InvalidNumberException that extends RuntimeException. Throw this exception if any
negative number is encountered in the array. Handle this custom exception in your program using a
try-catch block.

You might also like