S07L34 – Checked and unchecked exception in Java

Checked and Unchecked Exceptions in Java

Table of Contents

  1. Introduction
  2. What are Checked and Unchecked Exceptions?
  3. Difference Between Checked and Unchecked Exceptions
  4. Code Example: Handling Checked and Unchecked Exceptions
  5. Conclusion

Introduction

Exception handling is one of the most important aspects of Java programming. Java has two types of exceptions: checked and unchecked. Understanding the distinction between these types helps in writing robust and error-free applications. In this article, we will explore the differences between checked and unchecked exceptions with examples.

What are Checked and Unchecked Exceptions?

In Java, exceptions can be categorized into two main types:

  • Checked Exceptions: These are exceptions that the compiler checks during compile time. They must either be caught or declared in the throws clause of the method. Examples include IOException and SQLException.
  • Unchecked Exceptions: These exceptions occur during runtime. They do not need to be declared or caught, as they are typically less serious. Examples include NullPointerException and ArithmeticException.

Difference Between Checked and Unchecked Exceptions

The key difference between checked and unchecked exceptions lies in how they are handled by the Java compiler. Here’s a quick comparison:

Feature Checked Exception Unchecked Exception
Compile-time Checking Yes, must be caught or declared using throws. No, the compiler does not check for these.
Severity Typically more serious errors that should be handled. Usually less serious, can be avoided by proper code.
Examples IOException, SQLException NullPointerException, ArrayIndexOutOfBoundsException

Code Example: Handling Checked and Unchecked Exceptions

In the provided project, the Main.java class demonstrates how to handle checked exceptions.

Main Class:

Explanation:

Checked Exception: In this example, ZeroException is a custom checked exception. The method doSomething() declares that it can throw this exception using the throws keyword.
Unchecked Exception: If the code were to handle an unchecked exception, such as NullPointerException, there would be no need to declare or catch it, as Java does not require it at compile time.

Output:

Conclusion

Understanding the difference between checked and unchecked exceptions is critical in Java programming. Checked exceptions must be handled, either by catching them or by declaring them in the method signature. Unchecked exceptions, on the other hand, occur at runtime and do not require explicit handling. Proper use of exception handling ensures that programs are robust and able to deal with unexpected events.