Java Hamza 8
Java Hamza 8
Experiment No: 8
Objective :
To recognize usage of Exception Handling in various applications
Theory:
Exception Handling in Java is a mechanism that deals with runtime errors, ensuring
the normal flow of the program isn't disrupted by unexpected errors or exceptions.
An exception is an event that occurs during the execution of a program that disrupts
its normal flow.
Key Concepts:
1. Exception:
o An exception is an object that encapsulates an error event that occurs
during the execution of a program. In Java, exceptions are objects that
derive from the java.lang.Exception class.
o Example: Trying to divide a number by zero (ArithmeticException) or
accessing an invalid array index (ArrayIndexOutOfBoundsException).
2. Exception Hierarchy:
o Checked exceptions: These are exceptions checked at compile time.
They must be either handled using a try-catch block or declared in the
method signature with a throws clause. Examples include IOException,
SQLException.
o Unchecked exceptions (Runtime Exceptions): These occur during the
execution of a program. Unchecked exceptions do not need to be
declared or handled explicitly. They include errors like
NullPointerException, ArrayIndexOutOfBoundsException.
o Errors: These represent serious problems that are generally not
recoverable, such as OutOfMemoryError.
try: The block of code that is monitored for exceptions. If an exception occurs,
the control is transferred to the corresponding catch block.
catch: This block catches and handles the exception thrown in the try block.
You can have multiple catch blocks to handle different types of exceptions.
finally: The finally block always executes after the try and catch blocks,
regardless of whether an exception occurred or not. It's typically used for
resource cleanup, like closing file streams or database connections.
throws: This is used in the method signature to indicate that the method may
throw certain exceptions, which must be handled by the calling method.
4. Commonly Thrown Exceptions:
Conclusion:
Learned Exception Handling and Object Oriented Programming Concepts like
encapsulation and inheritance.