Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
3. Core APIs & I/O
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

21. Exceptions: Handling Runtime Errors

Stopping crashes gracefully when bad things happen.

Java Programming: From Zero to Enterprise
3. Core APIs & I/O
February 22, 2026
3.1K
A

[!NOTE] Even if your code compiles perfectly, real-world problems will occur while the program is actually running. A user might try to upload a corrupted file, the database server might catch fire, or the network might partition.

When Java encounters a fatal error during runtime, it throws an Exception. If you do not explicitly catch and handle that exception, your entire application will instantly crash.

The Try-Catch Block

The try-catch block allows you to anticipate potential failures and provide a safe fallback mechanism instead of a hard crash.

public class InputExample {
  public static void main(String[] args) {
    try {
      // 1. The DANGEROUS code goes in the 'try' block
      int[] myNumbers = {1, 2, 3};
      
      // FATAL ERROR! Index 10 does not exist!
      System.out.println(myNumbers[10]); 
      
      // This line is NEVER reached because the error immediately jumps to 'catch'
      System.out.println("Execution continues..."); 
      
    } catch (Exception e) {
      // 2. The FALLBACK code goes in the 'catch' block
      System.out.println("Something went wrong, but the app survived!");
      System.out.println("Developer Error Log: " + e.getMessage());
    }
  }
}

The 'finally' Block

Often, you open an expensive system resource (like a database connection or a file stream) in your try block. If an error occurs halfway through, the code jumps to catch, and your command to close that connection is bypassed!

The finally block executes no matter what happens. Even if a try block successfully returns, or a catch block catches an error, the finally block is guaranteed to execute before the method finishes.

Scanner scan = new Scanner(System.in);
try {
   int age = scan.nextInt(); 
   System.out.println("Valid age: " + age);
} catch (Exception e) {
   System.out.println("Please enter a valid number!");
} finally {
   // This code will always execute! Prevents memory leaks!
   scan.close(); 
   System.out.println("Scanner closed successfully.");
}

[!TIP] Catching Specific Errors: Instead of catching a generic Exception e, you should catch specific exceptions like NullPointerException or FileNotFoundException. This allows you to write custom fallback logic depending on exactly why the code failed.

Handling Exceptions Without Hiding Bugs

Exception handling is not about making errors disappear. It is about deciding which failures the program can recover from, which failures should be logged, and which failures should stop the operation immediately.

Catch Specific Exceptions First

try {
    int value = Integer.parseInt(input);
    System.out.println("Parsed: " + value);
} catch (NumberFormatException e) {
    System.out.println("Please enter a valid whole number.");
}

This is better than catching generic Exception because it documents the exact failure you expect. Catching everything can accidentally hide programming mistakes.

Log for Developers, Message for Users

A user-friendly message should explain what the user can do next. A developer log should keep technical detail such as exception type, message, and stack trace.

Common Mistakes

  • Catching Exception everywhere and continuing as if nothing happened.
  • Leaving catch blocks empty.
  • Showing raw stack traces directly to end users.
  • Using exceptions for normal control flow, such as checking if a list is empty.

Mini Practice

Write a method that converts a string into an integer. If parsing fails, show a clean message and return a default value. Then update it to log the original exception message for developers.

Practice Lab: Safe Number Parser

Practice handling bad runtime input without hiding the failure.

  1. Create a method parseMark(String input).
  2. Use Integer.parseInt(input) inside a try block.
  3. Catch NumberFormatException and return -1.
  4. Print a user-friendly message when parsing fails.
  5. Test inputs like "85", "abc", and "".

Goal: Catch a specific expected exception and keep the program flow controlled.

Revision Checkpoint

  • Exception: Runtime problem represented as an object.
  • try: Holds risky code.
  • catch: Handles a specific failure.
  • finally: Runs cleanup code.
  • Best habit: Catch specific exceptions and avoid empty catch blocks.

Before the quiz: Explain what should be shown to users and what should be logged for developers.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Exceptions
10 questions5 min
Lesson 1 of 10 in 3. Core APIs & I/O
Next in 3. Core APIs & I/O
22. The 'throw' and 'throws' keywords
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories