Java Checked vs Unchecked Exceptions Tutorial šŸŽÆ

beginner
24 min

Java Checked vs Unchecked Exceptions Tutorial šŸŽÆ

Welcome to this comprehensive guide on Java Checked and Unchecked Exceptions! By the end of this lesson, you'll have a solid understanding of these important concepts. Let's dive in! 🐠

What are Exceptions? šŸ“

An Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions enable you to create programs that can resolve problems and continue running instead of crashing.

Checked vs Unchecked Exceptions šŸ’”

In Java, Exceptions can be either Checked or Unchecked. Let's explore the differences and similarities between them.

Checked Exceptions šŸ“

Checked exceptions are subclasses of the Exception class that must be handled (either by catching them or declaring them in a method's throws clause). They are checked at compile-time and represent exceptions that are expected to occur due to programming errors or external conditions.

Example: IOException, SQLException

java
import java.io.*; public class CheckedExceptionExample { public static void main(String[] args) { try { // Writing to a non-existent file FileWriter fileWriter = new FileWriter("non_existent_file.txt"); fileWriter.write("Hello, World!"); fileWriter.close(); } catch (IOException e) { System.out.println("An I/O error occurred: " + e.getMessage()); } } }

šŸ“ Note: Always catch the most specific exception possible.

Unchecked Exceptions šŸ“

Unchecked exceptions are subclasses of the RuntimeException class that don't need to be declared in a method's throws clause and are only checked at runtime. They represent exceptions that are caused by programming errors such as NullPointerException, ArrayIndexOutOfBoundsException, and IllegalArgumentException.

Example: NullPointerException, ArrayIndexOutOfBoundsException

java
public class UncheckedExceptionExample { public static void main(String[] args) { String[] array = new String[3]; System.out.println(array[5]); // Unchecked exception: ArrayIndexOutOfBoundsException } }

Handling Exceptions šŸ“

There are several ways to handle exceptions in Java:

  1. Try-catch blocks: Catch and handle exceptions within a try-catch block.
  2. Throws clause: Declare that a method may throw an exception by listing it in the method's throws clause.
  3. Finally block: Used to release resources whether an exception occurs or not.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

Which of the following is an example of a Checked Exception?

That's it for this lesson! Stay tuned for more in-depth Java tutorials on CodeYourCraft. Happy coding! šŸš€