0
0
Javaprogramming~30 mins

Checked vs unchecked exceptions in Java - Hands-On Comparison

Choose your learning style9 modes available
Checked vs Unchecked Exceptions in Java
πŸ“– Scenario: Imagine you are writing a simple Java program that reads a file and processes its content. Sometimes, the file might not be found, or there might be an error in the program logic. Java uses two types of exceptions to handle these situations: checked and unchecked exceptions.
🎯 Goal: You will create a Java program that demonstrates the difference between checked and unchecked exceptions by handling a file reading operation and a division operation that might cause an error.
πŸ“‹ What You'll Learn
Create a method that throws a checked exception (FileNotFoundException).
Create a method that throws an unchecked exception (ArithmeticException).
Use try-catch blocks to handle the checked exception.
Do not handle the unchecked exception explicitly.
Print messages to show when exceptions are caught or when the program continues.
πŸ’‘ Why This Matters
🌍 Real World
Handling checked and unchecked exceptions is essential when working with files, databases, and user input in real-world Java applications.
πŸ’Ό Career
Understanding exception types helps developers write robust Java code that gracefully handles errors and improves software quality.
Progress0 / 4 steps
1
Create a method that throws a checked exception
Create a method called readFile that throws FileNotFoundException. Inside the method, write throw new FileNotFoundException("File not found").
Java
Need a hint?

Remember to declare the exception in the method signature using throws FileNotFoundException.

2
Create a method that throws an unchecked exception
Add a method called divide that takes two integers a and b and returns the result of a / b. This method will throw an unchecked ArithmeticException if b is zero.
Java
Need a hint?

Unchecked exceptions like ArithmeticException do not need to be declared in the method signature.

3
Handle the checked exception with try-catch
In the main method, call readFile() inside a try-catch block. Catch the FileNotFoundException and print "Caught checked exception: " followed by the exception message.
Java
Need a hint?

Use a try block to call readFile() and catch the exception with catch (FileNotFoundException e).

4
Call the unchecked exception method and print result
In the main method, after the try-catch block, call divide(10, 0) and print the result with System.out.println("Result: " + result). Do not use try-catch for this call.
Java
Need a hint?

Calling divide(10, 0) will cause an ArithmeticException and stop the program. This shows unchecked exceptions do not require try-catch.