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

Java Exception Handling Examples

The document contains 3 Java code examples that demonstrate different exception handling concepts: 1. The first example shows how to define and throw a custom exception called MyException when a negative number is entered. 2. The second example defines a BankAccount class that throws an InsufficientFundsException if a withdrawal exceeds the available balance. 3. The third example demonstrates try-with-resources, multi-catch exceptions, and exception propagation by defining methods that throw different exceptions and calling them within try-catch blocks.

Uploaded by

vnraids
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)
15 views3 pages

Java Exception Handling Examples

The document contains 3 Java code examples that demonstrate different exception handling concepts: 1. The first example shows how to define and throw a custom exception called MyException when a negative number is entered. 2. The second example defines a BankAccount class that throws an InsufficientFundsException if a withdrawal exceeds the available balance. 3. The third example demonstrates try-with-resources, multi-catch exceptions, and exception propagation by defining methods that throw different exceptions and calling them within try-catch blocks.

Uploaded by

vnraids
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

a. Write a Java program to implement user defined exception handling.

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}
public class UserDefinedException {
public static void main(String[] args) {
int number = 0;
try {
[Link] scanner = new [Link]([Link]);
[Link]("Enter a positive number: ");
number = [Link]();
[Link]();
if (number < 0) {
throw new MyException("Negative number entered");
}
[Link]("The number is " + number);
}
catch (MyException e) {
[Link]([Link]());
}
}
}

[Link] a Java program to throw an exception “Insufficient Funds” while withdrawing


the amount in the user account.
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private String owner;
private double balance;
private double minimumBalance;
public BankAccount(String owner, double balance, double minimumBalance) {
[Link] = owner;
[Link] = balance;
[Link] = minimumBalance;
}

public String getOwner() {


return owner;
}

public double getBalance() {


return balance;
}
public double getMinimumBalance() {
return minimumBalance;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("Invalid withdrawal amount");
}
if (amount > balance - minimumBalance) {
throw new InsufficientFundsException("Insufficient funds");
}
balance -= amount;
}
}
class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("Alice", 10000, 1000);
try {
[Link](5000);
[Link]("Withdrawal successful");
[Link]("New balance: " + [Link]());
} catch (InsufficientFundsException e) {
[Link]("Withdrawal failed");
[Link]([Link]());
} catch (IllegalArgumentException e) {
[Link]("Withdrawal failed");
[Link]([Link]());
}
}
}

c. Write a Java program to implement Try-with Resources, Multi-catch Exceptions,


and
Exception Propagation Concepts?

class Demo {
public static void method1() throws IOException {
throw new IOException("IO exception occurred");
}
public static void method2() throws ArithmeticException {
throw new ArithmeticException("Arithmetic exception occurred");
}
public static void method3() throws IOException, ArithmeticException {
method1();
method2();
}
public static void method4() throws IOException {
try (FileWriter fw = new FileWriter("[Link]")) {
[Link]("Hello world");
}
}
public static void main(String[] args) {
try {
method4();
[Link]("File written successfully");
} catch (IOException e) {
[Link]("IO exception: " + [Link]());
}
try {
method3();
} catch (IOException | ArithmeticException e) {
[Link]("Exception: " + [Link]());
}
}
}

Common questions

Powered by AI

Using checked versus unchecked exceptions strategically depends on whether the errors should be mandatorily managed by the developer. Checked exceptions, like IOException in method4 when handling file operations, require explicit handling or declaration, ensuring that the developer considers these error states during development, which can lead to more robust applications. Unchecked exceptions, such as IllegalArgumentException used in the withdraw method, are not required to be handled explicitly; they are typically used for programming errors, allowing the application to be more flexible and efficient by depending on proper input by design. Thus, the choice between them balances robustness, efficiency, and developer control .

Exception handling enhances the robustness and user experience of Java programs by providing a mechanism to gracefully handle runtime errors, ensuring that the application can recover from unexpected situations rather than failing abruptly. In banking applications, like the BankAccount example, exception handling allows specific error conditions such as insufficient funds or illegal withdrawal amounts to be managed with clear feedback to users through custom error messages. This not only prevents unplanned crashes but also gives users and developers clear insights into operational issues, improving usability and trust in the application .

To extend exception handling in an online shopping cart context, you can define a custom exception such as CartLimitExceededException. This exception can be thrown when a user attempts to add items exceeding the cart's predefined limit. The implementation would involve creating a class CartLimitExceededException extending Exception, and in the method addItem() of a ShoppingCart class, checking if the current item count plus new items exceeds capacity: if (currentItemCount + itemCount > maxCapacity) throw new CartLimitExceededException("Cart limit exceeded"). This provides specific error handling relevant to application logic, enhancing usability and control .

Validating withdrawal amounts is critical in banking applications to prevent transactions that may lead to breaches of the account, such as overdrawing beyond a safe minimum balance. If validation is incomplete, it could result in negative balances, violating contractual obligations to account holders and potentially causing significant financial and reputational damage. Using validations like checking if amount <= 0 in the withdraw method ensures only legitimate amounts are processed, and confirming sufficient balance prevents operations that would breach account terms, as illustrated when throwing InsufficientFundsException if funds aren't adequate .

Multi-catch blocks in Java are significant because they allow a single catch block to handle multiple exceptions, which simplifies the code and increases readability. By using a pipe (|), developers can specify several exception types that lead to the same handling logic. In the provided example, the method main in class Demo utilizes this concept by catching multiple exceptions thrown from method3 with the statement: catch (IOException | ArithmeticException e), thus demonstrating that both IOException and ArithmeticException could be handled with the same block of error processing code. This reduces redundancy and streamlines error handling .

Handling insufficient funds in a banking application can be achieved by defining a custom exception class such as InsufficientFundsException, which extends Exception. This exception is thrown when a withdrawal operation exceeds the available balance left after maintaining a specified minimum balance. The BankAccount class has a method withdraw that checks if the withdrawal amount is more than what's permissible, considering the minimum balance. If so, the InsufficientFundsException is thrown, as shown in: if (amount > balance - minimumBalance) throw new InsufficientFundsException("Insufficient funds");. This helps in accurately signaling problems over generic exceptions .

Exception propagation in Java refers to the process where an exception is thrown up the stack trace until it is caught by an appropriate handler or causes the program to terminate. In the context of the provided code, the method method3 throws both IOException and ArithmeticException by calling method1 and method2, respectively. If these exceptions are not handled within method3, they propagate to the calling method, which in the main method is managed using a multi-catch block: catch (IOException | ArithmeticException e). This exemplary handling demonstrates propagation by allowing exceptions thrown in lower methods to be caught at higher levels .

The try-with-resources statement is important in Java as it ensures that each resource is closed at the end of the statement. This feature simplifies resource management by automatically handling the closing of resources like file streams, which reduces the potential for resource leaks and enhances code reliability. An implementation example from the provided document involves writing to a file using: try (FileWriter fw = new FileWriter("output.txt")) { fw.write("Hello world"); }, ensuring the FileWriter is closed after the operation completes, whether successfully or due to an exception .

IllegalArgumentException plays a crucial role in method design by providing a means to flag incorrect or inappropriate arguments passed to a method, signaling that the parameters provided don't meet the method's requirements. In the banking application example, it is used in the withdraw method to ensure the withdrawal amount is positive. If an invalid amount is passed, the exception is thrown, stopping further processing and alerting the user that their input violated expected constraints. This ensures robustness by preventing invalid operations from proceeding .

User-defined exceptions in Java allow developers to create exceptions that are specific to their application’s context, offering more precise error reporting and control. This mechanism is implemented by extending the Exception class. For example, a Java program may define a MyException class that extends Exception, used to handle cases when a user inputs a negative number, as demonstrated with: class MyException extends Exception { public MyException(String message) { super(message); } }. In the provided code, when a negative number is entered by the user, this specific exception is thrown with a relevant message, thereby enhancing clarity and debugging capability .

You might also like