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

22. The 'throw' and 'throws' keywords

Creating your own errors and passing the buck up the chain.

Feb 22, 20264 views0 likes0 fires
18px

[!NOTE] Sometimes, an operation is mathematically "successful", but logically invalid for your business logic.

For example, a user trying to withdraw $10,000 when they only have $5 in their bank account. The mathematical subtraction of

5

  • 10000
will successfully result in -9995.

This is a business rule failure, not a Java compiler failure. We can force Java to treat this as a fatal error using the throw keyword.

The 'throw' Keyword (Manual Instigation)

The throw statement allows you to create a custom error instantly. By convention, you use this in conjunction with an if statement validating input parameters.

public class SecurityApp {  static void checkAge(int age) {    if (age < 18) {      // 1. Manually instantiate a new Error object and throw it at the JVM!      throw new ArithmeticException("Access denied

You must be at least 18 years old.");  } else {System.out.println("Access granted

You are old enough!");  }}
public static void main(String[] args) {  checkAge(15); // This will crash the app with our custom error message!}}


The 'throws' Keyword (Passing Responsibility)

Sometimes, you don't want to handle an exception inside a small utility method. If a readFile() method fails because the file is missing, it shouldn't be the utility method's job to decide what to show the user.

Using the throws keyword in a method signature warns anyone calling the method: "Hey, this method might explode with an error. I'm not going to catch it. If you call me, YOU must put me in a try-catch block."

import java.io.*;

public class Logger {
    // 1. We declare that this method throws an exception. 
    // We do NOT use try-catch inside this method body.
    public static void readSecureFile() throws FileNotFoundException {
        File myObj = new File("non_existent_passwords.txt");
        Scanner myReader = new Scanner(myObj); // Java knows this could fail
    }

    public static void main(String[] args) {
        // 2. Because readSecureFile() is marked with 'throws',
        // the compiler FORCES you to wrap the execution in a try-catch!
        try {
            readSecureFile();
        } catch (FileNotFoundException e) {
            System.out.println("The Main API routed a graceful 404 response to the user's browser.");
        }
    }
}

[!CAUTION] Checked Exceptions vs Unchecked Exceptions: Java requires you to handle (via try/catch or throws) "Checked" exceptions like IOException at compile time. However, logical "Unchecked" exceptions like NullPointerException or ArithmeticException are completely ignored by the compiler.

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: Throw & Throws
2 questions5 min

Continue Learning

23. Dates, Times, and Formatting

Beginner
8 min

24. Enumerable Data Structures

Beginner
10 min

25. LinkedLists: The Alternative

Intermediate
11 min
Lesson 2 of 10 in 3. Core APIs & I/O
Previous in 3. Core APIs & I/O
21. Exceptions: Handling Runtime Errors
Next in 3. Core APIs & I/O
23. Dates, Times, and Formatting
← Back to Java Programming: From Zero to Enterprise
Back to Java Programming: From Zero to EnterpriseAll Categories