Java Unit 5
Java Unit 5
Basic Exceptions
In Java, an exception is an event that occurs during the execution of a program
that disrupts the normal flow of instructions. Exceptions can be caused by various
factors, such as user input, invalid data, or hardware failure. In Java, exceptions are
objects that are instances of a subclass of the `Throwable` class.
Throw exceptions as close to the source of the error as possible: When an error
occurs, it's important to throw the exception as close to the source of the error
as possible. This makes it easier to pinpoint the cause of the error and to fix the
problem.
Provide informative error messages: When you create an exception, make sure to
provide an informative error message that explains what went wrong and how to
fix the problem. This can help users of your program to diagnose and fix errors
more easily.
Use finally blocks for cleanup code: If you need to perform some cleanup code, such
as closing a file or releasing a resource, use a finally block. This block will be
executed regardless of whether an exception was thrown or not.
Catching Exception:
The `try-catch` block is used to catch exceptions that may be thrown during
program execution. The `try` block contains the code that may throw an exception, and
the `catch` block is used to handle the exception if it is thrown. You can also `catch`
multiple types of exceptions using multiple catch blocks.