0% found this document useful (0 votes)
15 views4 pages

Java Exception Handling Examples

The document provides Java programs demonstrating various aspects of exception handling, including basic exception handling with try-catch-finally, multiple catch clauses for different exceptions, built-in exceptions like NullPointerException and NumberFormatException, and a user-defined exception. Each program includes explanations of how exceptions are caught and handled, along with example outputs. The document serves as a comprehensive guide to understanding Java's exception handling mechanism.

Uploaded by

kesavat0001
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)
15 views4 pages

Java Exception Handling Examples

The document provides Java programs demonstrating various aspects of exception handling, including basic exception handling with try-catch-finally, multiple catch clauses for different exceptions, built-in exceptions like NullPointerException and NumberFormatException, and a user-defined exception. Each program includes explanations of how exceptions are caught and handled, along with example outputs. The document serves as a comprehensive guide to understanding Java's exception handling mechanism.

Uploaded by

kesavat0001
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

A) Write a JAVA program that describes exception handling mechanism

Here’s a simple Java program that demonstrates exception handling using try, catch, and
finally blocks. This program attempts to divide two numbers and catches an
ArithmeticException if division by zero occurs.

Java Exception Handling


public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Attempting to divide by zero
int numerator = 10;
int denominator = 0;
int result = numerator / denominator;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
// Handling division by zero exception
[Link]("Exception Caught: Cannot divide by zero.");
} finally {
// Finally block always executes
[Link]("Execution completed.");
}
}
}

Output:
Exception Caught: Cannot divide by zero.
Execution completed.

Explanation:

 The try block contains code that may throw an exception.


 The catch block catches the ArithmeticException when division by zero is
attempted.
 The finally block executes regardless of whether an exception is thrown or not.

B) Write a JAVA program Illustrating Multiple catch clauses

public class MultipleCatchDemo {


public static void main(String[] args) {
try {
int[] numbers = {10, 20, 30};
int numerator = 10;
int denominator = 0;

// Attempting division by zero


int result = numerator / denominator;
[Link]("Result: " + result);
// Accessing an invalid index
[Link](numbers[5]);
} catch (ArithmeticException e) {
[Link]("Exception Caught: Cannot divide by zero.");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception Caught: Array index is out of bounds.");
} finally {
[Link]("Execution completed.");
}
}
}

Output:
Exception Caught: Cannot divide by zero.
Execution completed.

OR (if division is fixed and array index issue occurs)

Exception Caught: Array index is out of bounds.


Execution completed.

Explanation:

 The try block contains code that might throw exceptions.


 The first catch block handles ArithmeticException (division by zero).
 The second catch block handles ArrayIndexOutOfBoundsException (invalid array
index access).
 The finally block executes regardless of exceptions, ensuring clean-up or final
statements run.

C) Write a JAVA program for creation of Java Built-in Exceptions

public class BuiltInExceptionDemo {


public static void main(String[] args) {
try {
// NullPointerException Example
String str = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Exception Caught: Null pointer exception.");
}

try {
// NumberFormatException Example
String invalidNumber = "abc";
int num = [Link](invalidNumber);
[Link](num);
} catch (NumberFormatException e) {
[Link]("Exception Caught: Number format exception.");
}

try {
// ArrayIndexOutOfBoundsException Example
int[] arr = new int[5];
[Link](arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception Caught: Array index out of bounds exception.");
}
}
}

Output:
Exception Caught: Null pointer exception.
Exception Caught: Number format exception.
Exception Caught: Array index out of bounds exception.

Explanation:

 NullPointerException occurs when trying to access a method on a null object.


 NumberFormatException occurs when trying to convert an invalid string into a number.
 ArrayIndexOutOfBoundsException occurs when accessing an invalid array index.

D) Write a JAVA program for creation of User Defined Exception

class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

public class UserDefinedExceptionDemo {


public static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or above.");
} else {
[Link]("Valid age, access granted.");
}
}

public static void main(String[] args) {


try {
validateAge(16);
} catch (CustomException e) {
[Link]("Exception Caught: " + [Link]());
}
}
}

Output:
Exception Caught: Age must be 18 or above.

Explanation:

 A user-defined exception (CustomException) is created by extending Exception.


 The validateAge() method checks if the age is below 18 and throws the exception if true.
 The try-catch block handles the exception and prints the custom error message.

Common questions

Powered by AI

Exception handling enhances the robustness of a Java application by providing mechanisms to catch and handle errors gracefully, rather than allowing them to cause program crashes. This approach not only prevents abrupt program termination but also facilitates informed error reporting and adaptive recovery from unforeseen issues. It optimizes maintainability by centralizing error management, which simplifies debugging and modification processes. By separating error handling logic from regular code paths, exceptions allow developers to write cleaner, more readable code, leading to reduced complexity and increased focus on correct error logic . This structured error control is crucial for maintaining large applications over time, aiding in the evolution and enhancement of software with minimal disruption .

The absence of exception handling in critical Java applications can lead to severe impacts, including program crashes, data corruption, and insecure or inconsistent states that risk user safety and trust. Without a framework to manage errors, such as unhandled null references or illegal operations like division by zero, applications are prone to fail unpredictably. This undermines reliability and can lead to ungraceful termination or incorrect results, damaging user experience and potentially causing financial or operational losses. The structured approach of try, catch, and finally blocks mitigates such risks by ensuring errors are caught and handled gracefully, providing users with clarity on operational issues and maintaining application integrity .

An ArithmeticException, such as division by zero, disrupts the normal flow of a Java program by causing an abrupt termination of the operation if not handled. In the absence of appropriate exception handling, this can lead to program crashes or unpredictable behavior. Java mitigates this disruption through its exception-handling framework, wherein try-catch blocks are employed to catch such exceptions and execute alternative logic instead. For instance, attempting division by zero in the example program leads to an ArithmeticException, which is caught by a specific catch block that provides a user-friendly error message, 'Cannot divide by zero', while allowing the program to continue executing the finally block's necessary operations . This approach thus preserves program stability and gives users clear feedback on errors .

The use of multiple catch blocks in Java allows a program to handle different types of exceptions that might arise within a try block, enhancing the program's robustness. Each catch block is designed to handle a specific exception type, such as ArithmeticException or ArrayIndexOutOfBoundsException. This enables precise responses to different error conditions, providing clear and relevant error messages to users . If multiple exceptions are possible in a try block, defining separate handlers for each potential exception ensures that no exception is unintentionally ignored, leading to better debugging and user feedback .

A NullPointerException occurs in Java when an attempt is made to access an object with a null reference, such as calling a method on a null object. In the provided example, trying to access the length of a null String results in a NullPointerException . A NumberFormatException arises when an attempt is made to convert a String into a number but the String does not have an appropriate format, such as trying to parse 'abc' as an integer . An ArrayIndexOutOfBoundsException occurs when an attempt is made to access an array with an invalid index, such as trying to access the tenth element of an array with only five elements .

In a user-defined exception class in Java, the constructor plays a crucial role by allowing the transmission of a descriptive message when the exception is thrown. By extending from the Exception class, a custom exception can include constructors that accept parameters, such as error messages. In the provided example, the CustomException class defines a constructor that takes a String message and passes it to the superclass Exception. This message can then be retrieved via the getMessage() method when the exception is handled, providing context and details about the exception .

The try block serves as the core of Java's exception-handling strategy, guiding the entire flow of error detection and management. By designating a block of code where exceptions might occur, the try construct allows the programmer to anticipate and manage potential run-time errors systematically. Within a try block, code is executed normally, but should an error, such as division by zero or invalid array access, occur, the program control shifts immediately to a corresponding catch block . This preemptive frame enables developers to encapsulate error-prone operations deliberately and define multiple resolution pathways, ensuring that errors are met with structured responses rather than unpredictable program termination .

Java handles exceptions using a combination of try, catch, and finally blocks. The try block contains code that might throw an exception. If an exception occurs within the try block, the flow of control shifts to the corresponding catch block, which handles the specific exception. The catch block is designed to catch exceptions of a particular type, such as ArithmeticException . Even if no exception is thrown, the finally block executes to perform any necessary cleanup or concluding operations, ensuring that essential code runs regardless of how the preceding try or catch blocks end. For example, releasing resources or closing files could be placed in a finally block .

In Java, user-defined exceptions allow developers to create exceptions tailored to specific application needs. This is achieved by defining a new class that extends the Exception class. For instance, a CustomException can be created for specific error scenarios by including meaningful error messages relevant to the application context. In the given example, a custom exception is created to check the validity of an age parameter. If the age is less than 18, a CustomException is thrown with the message 'Age must be 18 or above.' This application-specific exception clearly communicates the error condition to the user and handles it appropriately by outputting the custom message . Creating user-defined exceptions enhances clarity and control in managing application-specific logic errors .

The finally block in Java is designed to ensure that essential code executes irrespective of whether an exception is thrown or caught in the try-catch block. It provides a mechanism to release resources, perform cleanup operations, or execute concluding tasks that must be run, regardless of the program's state after the try-catch block. For instance, in the provided examples, the finally block contains a print statement indicating that execution is complete, demonstrating its reliability in executing crucial code sections post-exception handling . This makes the finally block a critical component in resource management frameworks, such as closing file I/O streams and database connections, thereby preventing resource leaks. .

You might also like