1.
Imagine you're building a system in Java where you
query a list of records (like an array). The user provides an
ID, and the system retrieves the corresponding record.
However, there are potential errors that can occur:
● IndexOutOfBoundsException: Raised if the user requests a
record with an ID that doesn't exist in the list (i.e., the ID is
out of bounds).
● NumberFormatException: Raised if the user enters a
non-numeric ID (for example, entering a string instead of a
number).
To handle these situations, you'll use exception handling in
Java. This allows you to gracefully catch and respond to these
errors rather than letting the program crash.
[Link] a Java program to simulate a bank account withdrawal.
Implement a BankAccount class with a withdraw method.
If the withdrawal amount exceeds the balance, use throw to
generate an InsufficientFundsException. If the
amount is negative, throw an
IllegalArgumentException. Use throws to declare
possible exceptions in the withdraw method. In the main
program, handle these exceptions with try-catch, and use a
finally block to print the final balance.
[Link] an EventRegistration class that requires a
minimum age for participation and includes a custom
exception, UnderageException, to handle underage
registration attempts. The class should initialize with a
minimum age requirement and contain a register
method that takes a participant’s name and age as input. If
the participant’s age is below the required minimum, the
method should raise an UnderageException with a
message specifying the age restriction. If the age
requirement is met, the method should confirm successful
registration. For example, if the minimum age is set to 18,
attempting to register someone aged 16 should raise the
UnderageException, while a participant aged 20
would be registered successfully.
[Link] you're building a basic system to query records
from a CSV file acting like a simple database. The user
provides a record ID to retrieve, but there are several
things that can go wrong. For example, if the file doesn’t
exist, a FileNotFoundError is raised. If the user enters a
non-numeric ID or an invalid value, a ValueError occurs. If
the ID is out of range (e.g., there’s no record with that ID),
you’ll encounter an IndexError. Additionally, general
IOErrors might happen if there are file permission issues or
the file can't be accessed for some reason. Using Python’s
built-in exceptions, you can handle these errors gracefully,
giving the user clear feedback about what went
wrong—whether the file is missing, the ID is invalid, or
there’s a general issue with the system. This ensures the
program doesn’t crash unexpectedly and provides a
smoother user experience.