Thursday, September 14, 2023

Checked Exceptions & Unchecked Exceptions

                                                  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:

 Checked exceptions are exceptions that the Java compiler requires you to handle explicitly in your code. This means that if a method can potentially throw a checked exception, you must either catch and handle that exception using a

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):

 Unchecked exceptions, also known as runtime exceptions, are exceptions that the compiler does not require you to handle explicitly. These exceptions usually

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[] numbers = {1, 2, 3};

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.


 

 

       *****Program for Checked Exception in Java*******

 

 

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

 

       *****Program for Unchecked Exception in java*****

 

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)

 

19 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Need more program and theory to practice more

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Quite understandable and useful content.

    ReplyDelete
  7. This page is more useful and we need more information on theory part and thankyou for giving this content

    ReplyDelete
  8. It is very understandable thank you sir

    ReplyDelete
  9. Need some interview questions sir

    ReplyDelete

Machine Learning Course Assignments 2024(Dec)

 Machine Learning Course Assignments 2024 1)   Explain the concept of "generalization" in machine learning. Why is it a central go...