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.

Feb 22, 20264 views0 likes0 fires
18px

[!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.

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
2 questions5 min

Continue Learning

22. The 'throw' and 'throws' keywords

Intermediate
10 min

23. Dates, Times, and Formatting

Beginner
8 min

24. Enumerable Data Structures

Beginner
10 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 Java Programming: From Zero to EnterpriseAll Categories