Exceptions
Exceptions
are a mechanism used to handle unexpected or exceptional situations that can occur during the execution of a program.
Java categorizes exceptions into two main types: checked
exceptions and unchecked exceptions (also
known as runtime exceptions). These two categories serve different purposes
and have different characteristics.
Checked Exceptions:
try-catch block or declare
that the method
throws the exception
using the throws
keyword in its method signature.
Common examples
of checked exceptions include IOException, SQLException, and ClassNotFoundException.
Checked
exceptions typically represent external problems or issues that your program may encounter during its
execution, such as file I/O errors or database
connection problems. Handling
these exceptions ensures
that your program
can gracefully recover
from these situations or report errors
to the user.
Example of handling a checked exception:
code:
try {
// Code that may throw a checked exception FileInputStream file = new FileInputStream("example.txt");
} catch (IOException e) {
// Handle
the exception
System.out.println("An error
occurred: " + e.getMessage());
}
Unchecked Exceptions (Runtime
Exceptions):
indicate programming errors or issues
that can be avoided through
proper coding practices.
Common examples
of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
Unchecked exceptions typically occur due to logical
errors in the code, such as attempting to access a null reference or
dividing by zero. While you are not forced
to handle them, it's still a good practice to do so when possible to make your code more robust.
Example of an unchecked exception:
int result
= numbers[5]; // This will throw an ArrayIndexOutOfBoundsException at runtime
In summary,
the key difference between checked
and unchecked exceptions in Java is that
checked exceptions must be explicitly handled or declared, while unchecked exceptions (runtime exceptions)
do not require explicit handling but should
still be addressed when possible. Effective exception handling is an essential part of writing reliable and
robust Java programs, as it allows you to gracefully
handle unexpected situations and provide meaningful feedback to users.
**** Difference between checked and unchecked exceptions****
Aspect |
Checked Exceptions |
Unchecked Exceptions |
Declaration in Code |
Must be declared using the throws
clause in the method signature or
handled using a try-catch block. |
Optional to declare or
handle. You can still use a
try-catch block, but it's not
required. |
Examples |
IOException, SQLException, ClassNotFoundException |
NullPointerException, ArrayIndexOutOfBoundsExceptio n, IllegalArgumentException |
Compiler Enforcement |
The compiler enforces handling or declaring checked exceptions at compile-time. |
The compiler does not
enforce handling or declaring
unchecked exceptions at compile-time. |
Handling Requirement |
Mandatory handling or declaration, either through a try-catch block or by propagating the exception using
the throws clause. |
Optional handling; you can choose whether or not to handle unchecked exceptions. |
Checked by Compiler |
Checked exceptions are checked by the compiler to ensure that they are properly handled or declared |
Unchecked exceptions are
not checked by the compiler, meaning that the compiler does not enforce handling or declaration. |
Extending Throwable |
Subclasses of Exception (excluding RuntimeException) and its subclasses
are considered checked exceptions. |
Subclasses of
RuntimeException and its
subclasses are considered unchecked exceptions. |
Inheritance Hierarchy |
Checked exceptions are typically further up the exception hierarchy and inherit from Exceptions. |
Unchecked exceptions are typically further down the hierarchy and inherit from RuntimeException |
Propagating Exceptions |
Checked exceptions need to be declared using the throws keyword in the method signature if they are not
handled locally. |
Unchecked exceptions do
not need to be declared using the throws keyword, even if they are not
handled locally. |
Try- Catch Block
Requirement |
Required for checked exceptions if you don't use the throws clause for declaration. |
Optional for unchecked exceptions; you can still use try-catch blocks if desired. |
public class
CheckedException {
public static void main(String[] args) { int dividend = 10;
int divisor
= 0;
try {
int result = dividend / divisor; System.out.println("Result: "
+ result);
} catch (ArithmeticException e) {
// Handle the checked exception (ArithmeticException) System.err.println("An error occurred: " + e.getMessage());
}
}
}
Output:
An error occurred: / by zero
public class UncheckedExceptionExample { public static
void main(String[] args) {
int[] numbers
= { 1, 2, 3, 4, 5 };
// Attempt to access an index that is out of bounds
int index = 10;
int value = numbers[index];
System.out.println("Value at index "
+ index + ": " + value);
// This line won't be reached
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds
for length 5
at
UncheckedExceptionExample.main(UncheckedExceptionExample.java:8)
Yes it is very use full sir
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteWe need more complex programs
ReplyDeleteNeed more program and theory to practice more
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteWe need briefly logical programs
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteIt's very useful content.
ReplyDeleteVery interesting programs
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteWe need more content sir
ReplyDeleteNeed more advanced content
ReplyDeleteNeed some challenging programs
ReplyDeleteIt is useful to practical exams
ReplyDeleteQuite understandable and useful content.
ReplyDeleteThis page is more useful and we need more information on theory part and thankyou for giving this content
ReplyDeleteThis content is very useful sir
ReplyDeleteIt is very understandable thank you sir
ReplyDeleteNeed some interview questions sir
ReplyDelete