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

java w 6 rec

The document provides a comprehensive overview of exception handling in Java, including the use of try-catch blocks, finally blocks, and the distinction between checked and unchecked exceptions. It includes multiple Java program examples demonstrating exception handling, multiple catch clauses, built-in exceptions, and user-defined exceptions. The programs illustrate how to manage errors effectively and ensure robust application behavior.

Uploaded by

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

java w 6 rec

The document provides a comprehensive overview of exception handling in Java, including the use of try-catch blocks, finally blocks, and the distinction between checked and unchecked exceptions. It includes multiple Java program examples demonstrating exception handling, multiple catch clauses, built-in exceptions, and user-defined exceptions. The programs illustrate how to manage errors effectively and ensure robust application behavior.

Uploaded by

Praveena
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

DATE EXP Page

: No: no:
16. Write a JAVA program that describes exception handling
mechanism. Aim: To write a program to implement exception
handling mechanism. Description:
Exception handling in Java is a powerful mechanism that allows
developers to manage runtime errors, ensuring that the program can
continue executing or terminate gracefully. It uses keywords like ‘try’,
‘catch’, ‘finally’,’ throw’, and throws to handle exceptions effectively.
In a typical scenario, code that might throw an exception is placed inside
a ‘try’ block. If an exception occurs, control is transferred to the
corresponding ‘catch’ block, where the exception can be handled. The
‘finally’ block can be used to execute code that must run regardless of
whether an exception occurred or not.
Key Concepts of Exception Handling in Java
 Try-Catch Block: Used to handle exceptions. Code that may throw an
exception is placed in the ‘try’ block, and the handling code is in
the ‘catch’ block.
 Finally Block: This block is optional and is executed after
the ‘try’ and ‘catch’ blocks, regardless of whether an exception was
thrown or not.
 Throw and Throws: The ‘throw’ keyword is used to explicitly throw
an exception, while ‘throws’ is used in method signatures to declare
that a method can throw exceptions.
 Checked vs Unchecked Exceptions: Checked exceptions must be
either caught or declared in the method signature, while unchecked
exceptions do not require explicit handling.
This structured approach to exception handling helps maintain the flow of
the program and provides a way to manage errors effectively.

Program code:
package week6;
import java.util.Scanner;
class WeightLimitExceeded extends Exception {
WeightLimitExceeded(int weight) {
super("Weight limit exceeded by " + Math.abs(15 - weight) + " kg");
}
}

public class Main {

OOPS through CSE


DATE EXP Page
: No: no:

void validWeight(int weight) throws


WeightLimitExceeded { if (weight > 15) {
throw new WeightLimitExceeded(weight);
} else {
System.out.println("You are ready to fly!");
}
}

public static void main(String[] args)


{ Main ob = new Main();
Scanner in = new
Scanner(System.in); for (int i = 0; i
< 2; i++) {
System.out.print("Enter
weight: "); try {
int weight = in.nextInt(); // Read user input
ob.validWeight(weight); // Validate weight
} catch (WeightLimitExceeded e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid
integer."); in.next();
}
}
in.close();
}
}

Sample Output:
C:\23-518>javac
Main.java C:\23-
518>java Main Enter
weight: abc
Invalid input. Please enter a valid
integer. Enter weight: 16
Weight limit exceeded by 1 kg.

OOPS through CSE


DATE EXP Page
: No: no:
Executed Output:
C:\23-518>javac
Main.java C:\23-
518>java Main
Enter weight: 15
You are ready to fly!
Enter weight: 45
Weight limit exceeded by 30 kg.

Result:
Hence, the program to implement exception handling mechanism has
been executed successfully.

17. Write a JAVA program Illustrating Multiple catch


clauses. Aim: To write a program to illustrate multiple
catch clauses.
Description:
In Java, multiple catch clauses are used to handle different types of
exceptions that may arise from a single try block. This feature allows
developers to define specific error handling logic for various exceptions
without duplicating the try block for each exception type.
Key Points:
 Single Try Block: A single try block can be followed by multiple
catch blocks to handle different exceptions.
 Specific Handling: Each catch block can specify a different
exception type, enabling tailored responses based on the
exception encountered.
 Java 7 and Later: Since Java 7, developers can also combine multiple
exception types in a single catch block using the pipe (|) operator,
which reduces redundancy in code.
 Order of Catch Blocks: When using multiple catch blocks, they
should be ordered from the most specific to the most general
exception type to avoid unreachable code errors.
Benefits:
 Improved Code Organization: It leads to cleaner and more
organized error handling.

OOPS through CSE


DATE EXP Page
: No: no:
 Enhanced Readability: Each exception type can be handled
distinctly, making the code easier to read and maintain.
 Robustness: It allows for more robust applications by gracefully
handling various error scenarios.

Program code:
package week6;
import java.util.Scanner;

public class MultipleCatchExample


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

System.out.println("Enter two integers to

divide:");

try {
int num1 =
scanner.nextInt(); int
num2 =
scanner.nextInt(); int
result = num1 / num2;
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
catch (java.util.InputMismatchException e) {
System.out.println("Error: Please enter valid integers.");
}
catch (Exception e) {
System.out.println("Error: An unexpected error occurred: " +
e.getMessage());
}
finally {
scanner.close();
}

OOPS through CSE


DATE EXP Page
: No: no:
}
}

OOPS through CSE


DATE EXP Page
: No: no:
Sample Output:
C:\23-518>javac
MultipleCatchExample.java C:\23-
518>java MultipleCatchExample
Enter two integers to divide:
20
10
Result: 2

Executed Output:
C:\23-518>javac
MultipleCatchExample.java C:\23-
518>java MultipleCatchExample
Enter two integers to divide:
18
2
Result: 9

Result:
Hence, the program to illustrate multiple catch clauses has been
executed successfully.

18. Write a JAVA program for creation of Java Built-in


Exceptions. Aim: To write a program to create java built-in
exceptions. Description:
Categories of Built-in Exceptions
Java exceptions can be broadly classified into two categories:
1. Checked Exceptions:
 These exceptions are checked at compile-time. The Java
compiler requires that these exceptions be either caught using a
try-catch block or declared in the method signature using the
throws keyword.
 Examples:
 IOException: Thrown when an input or output operation
fails or is interrupted.

OOPS through CSE


DATE EXP Page
: No: no:
 SǪLException: Thrown when there is an error with database
access.
 ClassNotFoundException: Thrown when an application
tries to load a class through its string name but cannot
find it.
2. Unchecked Exceptions:
 These exceptions are not checked at compile-time, meaning
the compiler does not require them to be handled. They typically
indicate programming errors or logical flaws in the code.
 Examples:
 NullPointerException: Thrown when an application
attempts to use null in a case where an object is
required.
 ArrayIndexOutOfBoundsException: Thrown when an array
has been accessed with an illegal index (either negative or
greater than or equal to the size of the array).
 ArithmeticException: Thrown when an exceptional
arithmetic condition occurs, such as division by zero.
Common Built-in Exceptions
Here is a brief overview of some commonly used built-in exceptions in
Java:
1. ArithmeticException
 Description: Occurs when an exceptional arithmetic
condition occurs, such as division by zero.
2. NullPointerException
 Description: Thrown when the application attempts to use null
where an object is required.
3. ArrayIndexOutOfBoundsException
 Description: Thrown when trying to access an array with an illegal
index.
4. ClassNotFoundException
 Description: Thrown when the Java Virtual Machine (JVM)
cannot find a class that is being referenced.
5. IOException
 Description: Signals that an I/O operation has failed or been
interrupted.
6. SǪLException
 Description: Provides information on a database access error
or other errors related to SǪL operations.

OOPS through CSE


DATE EXP Page
: No: no:
Program code:
package week6;
public class
BuiltInExceptionsExample {
public static void main(String[]
args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Division by zero is not
allowed.");
}
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException: Attempted to access a
method on a null object.");
}

try {
int[] arr = new int[5];
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: Index is out of
bounds.");
}
try {
Class.forName("com.example.NonExistentClass");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException: The specified class
was not found.");
}
}
}

Sample Output:
C:\23-518>javac
BuiltInExceptionsExample.java C:\23-

OOPS through CSE


DATE EXP Page
: No: no:
518>java BuiltInExceptionsExample

OOPS through CSE


DATE EXP Page
: No: no:
ArithmeticException: Division by zero is not allowed.
NullPointerException: Attempted to access a method on a null object.
ArrayIndexOutOfBoundsException: Index is out of bounds.
ClassNotFoundException: The specified class was not found.

Executed Output:
C:\23-518>javac
BuiltInExceptionsExample.java C:\23-
518>java BuiltInExceptionsExample

ArithmeticException: Division by zero is not allowed.


NullPointerException: Attempted to access a method on a null object.
ArrayIndexOutOfBoundsException: Index is out of bounds.
ClassNotFoundException: The specified class was not found.

Result:
Hence, the program to create java built-in exceptions has been executed
successfully.

19. Write a JAVA program for creation of User Defined


Exception. Aim: To write a program for creation of user
defined exception. Description:

A user-defined exception in Java is a custom exception that developers


create to handle specific error conditions that are not adequately covered
by the standard Java exceptions. By extending the built-in Exception class
(for checked exceptions)
or RuntimeException class (for unchecked exceptions), developers can
define their own exception types that provide more meaningful error
handling in their applications.
Key Features of User-Defined Exceptions
1. Custom Behavior: User-defined exceptions allow developers to define
specific error conditions relevant to their application's business logic,
providing clearer and more informative error messages.
2. Extensibility: They can be extended from existing exception
classes, allowing developers to inherit properties and methods

OOPS through CSE


DATE EXP Page
: No: no:
from standard exceptions.

OOPS through CSE


DATE EXP Page
: No: no:
3. Granularity: By creating specific exceptions for different error
scenarios, developers can handle exceptions more granularly,
making the code easier to maintain and debug.
4. Checked vs. Unchecked: User-defined exceptions can be created
as checked exceptions (requiring explicit handling) or unchecked
exceptions (not requiring explicit handling). This choice depends
on how critical the exception is to the application's flow.
When to Use User-Defined Exceptions
 When standard exceptions do not provide sufficient context or
information about an error.
 To represent application-specific error conditions that need to be
handled distinctly.
 To improve code readability and maintainability by clearly defining the
types of errors that can occur.
Example
For instance, if you have a banking application, you might create a user-
defined exception called InsufficientFundsException to handle cases
where a withdrawal amount exceeds the available balance. This makes it
clear what the error is, rather than relying on a generic exception.

Program code:
package week6;
class InvalidAgeException extends
Exception { public
InvalidAgeException(String message) {
super(message);
}
}

public class UserDefinedExceptionDemo {

public static void checkAge(int age) throws


InvalidAgeException { if (age < 0 || age > 150) {
throw new InvalidAgeException("Age must be between 0 and 150.");
} else {
System.out.println("Age is valid: " + age);
}

OOPS through CSE


DATE EXP Page
: No: no:
}

public static void main(String[]


args) { try {
checkAge(2
5);
checkAge(-
5);
} catch (InvalidAgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}

try {
checkAge(200);
} catch (InvalidAgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}

Sample Output:
C:\23-518>javac
UserDefinedExceptionDemo C:\23-
518>java UserDefinedExceptionDemo

Age is valid: 25
Caught exception: Age must be between 0 and
150. Caught exception: Age must be between 0
and 150.

Executed Output:
C:\23-518>javac
UserDefinedExceptionDemo C:\23-
518>java UserDefinedExceptionDemo

Age is valid: 25
Caught exception: Age must be between 0
and 150. Caught exception: Age must be

OOPS through CSE


DATE EXP Page
: No: no:
between 0 and 150. Result:
Hence, the program to create user defined exception has been executed
successfully.

OOPS through CSE


DATE EXP Page
: No: no:

OOPS through CSE

You might also like