Skip to content

Throwing Exception in Java

This is when your code encounters an error condition and decides to raise an exception to signal that something went wrong. You can throw exceptions explicitly using the throw keyword, like tossing a lifebuoy to signal distress.

But why would you want to throw an exception? Imagine you're writing a program to divide two numbers. What if someone tries to divide by zero? That's a big no-no in math, right? So, you throw an exception to let them know they're trying something fishy.

Example

java
public class Divider {
    public double divide(int dividend, int divisor) {
        if (divisor == 0) {
            throw new ArithmeticException("Cannot divide by zero!");
        }
        return (double) dividend / divisor;
    }
}

public class ExceptionExample {
    public static void main(String[] args) {
        Divider divider = new Divider();
        try {
            double result = divider.divide(10, 0);
            System.out.println("Result of division: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Oops! Something went wrong: " + e.getMessage());
        }
    }
}

Ahoy! In our example, we have a Divider class that attempts to divide two numbers. But if the divisor is zero (a big no-no in math land), we throw an ArithmeticException with a helpful message.

But wait, there's more! We're not just throwing exceptions into the abyss—we're also catching them like seasoned sailors. In our main method, we use a try-catch block to catch any exceptions that might be thrown by the divide method.

Throws keyword

. When a method might encounter an exceptional situation that it can't handle on its own, it can declare that it "throws" a particular type of exception, passing the responsibility to its caller to deal with it.

Now, let's dive into an example to bring this concept to life:

java
public class FileReader {
    public String readFile(String filePath) throws FileNotFoundException {
        // Imagine some code to read from a file
        // For simplicity, let's just assume we're trying to open a file

        if (!fileExists(filePath)) {
            throw new FileNotFoundException("File not found: " + filePath);
        }

        // If the file exists, read it and return its content
        return "Content of the file: ...";
    }

    private boolean fileExists(String filePath) {
        // Imagine some code to check if the file exists
        return false; // For simplicity, always return false
    }
}

public class ThrowsExample {
    public static void main(String[] args) {
        FileReader fileReader = new FileReader();
        
        try {
            String content = fileReader.readFile("example.txt");
            System.out.println(content);
        } catch (FileNotFoundException e) {
            System.out.println("Oops! Something went wrong: " + e.getMessage());
        }
    }
}

In our example, the readFile() method in the FileReader class declares that it "throws" a FileNotFoundException if the file being read is not found. This means that whoever calls this method needs to be prepared to handle such an exception.

Now, let's journey through our code and witness the power of "throws" in action. When we attempt to read a file in the main() method, we wrap it in a try-catch block to catch any potential FileNotFoundException. This way, we gracefully handle the situation, preventing our program from crashing.

But wait, there's more to "throws" than just catching exceptions! It also allows methods to propagate exceptions up the call stack, providing flexibility and clarity in our code. By declaring the exceptions that a method might throw, we communicate to other developers what they need to watch out for when using our code.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.