Exception Handling :
Exception handling in Java refers to the mechanism through which errors or exceptional conditions that occur during the program execution are managed and resolved. It allows programmers to handle and recover from runtime errors gracefully, ensuring that the program does not terminate abruptly.
Exception
class is the base class for all exceptions. It is part of the Java standard library and is used as the superclass for all built-in and user-defined exceptions. The Exception
class itself extends the Throwable
class.
Exception abnormally terminates the execution of the program.
Example:-
public class Example{
statement--1
statement--2
statement--3
statement--4(Exception occurs at line 4)
statement--5
}
In Line no.4 Exception occurs so that statement -5 does not execute.
To handle exceptions use 5 key words.
1. try
2. catch
3. finally
4. throw
5. throws
Exception Handling By using try-catch:
In Java, you can handle exceptions using the try-catch
block. The try
block contains the code that might throw an exception and the catch
the block is responsible for catching and handling the exception. Here's the basic syntax:
javatry {
// Code that might throw an exception
} catch (ExceptionType1 exceptionVariable1) {
// Exception handling code for ExceptionType1
} catch (ExceptionType2 exceptionVariable2) {
// Exception handling code for ExceptionType2
}
finally {
// Optional finally block for cleanup code
}
Let's break down the steps for handling exceptions:
Place the code that might throw an exception within the
try
block. This is the code where you expect an exceptional condition to occur.Specify one or more
catch
blocks immediately after thetry
block. Eachcatch
block handles a specific type of exception. You need to provide the exception type and assign it to a variable that will hold the exception object.If an exception occurs within the
try
block, the correspondingcatch
block that matches the exception type is executed. The exception object is assigned to the specified variable, allowing you to access information about the exception and perform appropriate error handling.You can have multiple
catch
blocks to handle different types of exceptions. Thecatch
blocks are evaluated sequentially, and only the first matching block is executed. You can have a generalcatch
block that catches all types of exceptions by specifyingException
as the exception type.Optionally, you can include a
finally
block after thecatch
block(s). Thefinally
block contains code that is executed regardless of whether an exception occurred or not. It is commonly used for cleanup operations or releasing resources.
Here's an example that demonstrates exception handling:
javapublic class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
// Division by zero
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("An arithmetic exception occurred: " + e.getMessage());
} finally {
System.out.println("Cleanup code executed.");
}
}
public static int divide(int num1, int num2) {
return num1 / num2;
}
}
In this example, the divide
method attempts to divide two numbers. However, if the second number is zero, it will throw an ArithmeticException
in the try
block. The catch
block catches this exception, and the appropriate error message is displayed. The finally
block is executed regardless of the exception, ensuring that the cleanup code is performed.
By handling exceptions, you can control the flow of your program and provide appropriate error handling for exceptional conditions, preventing the program from crashing and allowing it to recover gracefully.
Type of Exception:
Exceptions are categorized into two types: checked exceptions and unchecked exceptions. These types determine how exceptions are handled by the Java compiler and whether they need to be explicitly handled or declared.
Checked Exceptions: Checked exceptions are exceptions that are checked by the Java compiler at compile-time. If a method throws a checked exception, the caller of that method must handle the exception or declare it in its own
throws
clause. Examples of checked exceptions in Java include:IOException
: Occurs during input/output operations, such as reading from or writing to files.SQLException
: Occurs when there are errors in database access or SQL operations.ClassNotFoundException
: Occurs when a class is not found at runtime.
To handle a checked exception, you need to catch it using a
try-catch
block or declare it in athrows
clause.Unchecked Exceptions: Unchecked exceptions, also known as runtime exceptions, are exceptions that are not checked by the Java compiler at compile-time. They can occur at runtime due to various factors such as programming errors, invalid inputs, or unexpected conditions. Unchecked exceptions do not require explicit handling or declaration. Some common examples of unchecked exceptions in Java include:
NullPointerException
: Occurs when a null reference is used where an object is expected.ArrayIndexOutOfBoundsException
: Occurs when an invalid array index is accessed.IllegalArgumentException
: Occurs when an invalid argument is passed to a method.
Unchecked exceptions are subclasses of the
RuntimeException
class or its subclasses. These exceptions are not enforced to be caught or declared.
By categorizing exceptions into checked and unchecked types, Java provides a mechanism to distinguish between exceptions that are expected and should be explicitly handled (checked exceptions) and exceptions that indicate programming errors or unexpected conditions (unchecked exceptions). This distinction helps in writing more robust and maintainable code by ensuring that critical exceptions are handled appropriately while allowing the flexibility to handle or propagate runtime exceptions as needed.
throw and throws:
In Java, the throw
and throws
keywords are used in exception handling, but they serve different purposes:
throw: The
throw
keyword is used to explicitly throw an exception from a method or block of code. It is followed by an instance of an exception class or a subclass ofThrowable
. When an exception is thrown, the normal flow of the program is disrupted, and the execution is transferred to an appropriatecatch
block that can handle the thrown exception.Here's an example of using the
throw
keyword:javapublic void checkAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } }
In this example, the
checkAge
method throws anIllegalArgumentException
if the provided age is negative. Thethrow
keyword is used to create and throw the exception object.throws: The
throws
keyword is used in a method declaration to specify that the method may throw one or more types of exceptions. It is used to indicate the potential exceptions that can occur within a method but are not handled within the method itself. Thethrows
clause is followed by a comma-separated list of exception types.Here's an example of using the
throws
keyword:javapublic void readFile() throws IOException, FileNotFoundException { // Code that might throw IOException or FileNotFoundException }
In this example, the
readFile
method is declared with thethrows
clause, indicating that it may throwIOException
orFileNotFoundException
. This informs the caller of the method that they need to handle or propagate these exceptions.When a method declares that it
throws
an exception, it is the responsibility of the calling code to handle the exception using atry-catch
block or propagate the exception by declaring it in its ownthrows
clause.Additionally, the
throws
keyword is also used in the declaration of constructors and in method overloading to indicate that the constructor or overloaded method can potentially throw certain exceptions.
Both throw
and throws
are essential in Java exception handling. The throw
keyword is used to explicitly throw exceptions, while the throws
keyword is used in method declarations to indicate the exceptions that might be thrown by that method.
0 Comments