Try catch

In Java, try, catch, and throws are part of the exception handling system. They let you deal with errors without crashing your program.

Here’s the breakdown:


1. try

  • A block of code where you write code that might throw an exception.
  • If an exception happens inside try, Java will look for a matching catch block.
try {
    int result = 10 / 0; // risky code
} 

2. catch

  • A block that handles the exception thrown by the try block.
  • You can have multiple catch blocks for different exception types.
catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}

3. throws

  • A method-level declaration that says, “This method might throw these exceptions, and I’m not handling them here—someone else must handle them.”
  • Used in the method signature, not inside the method body.
public void riskyMethod() throws IOException {
    FileReader fr = new FileReader("file.txt");
}

Putting It Together

public class Example {
    public static void main(String[] args) {
        try {
            riskyMethod();  // may throw IOException
        } catch (IOException e) {
            System.out.println("File error: " + e.getMessage());
        }
    }

    public static void riskyMethod() throws IOException {
        FileReader fr = new FileReader("missing.txt");
    }
}

Quick summary table:

KeywordWhere usedPurpose
tryInside methodCode that might throw an exception
catchInside methodHandles a thrown exception
throwsMethod signatureDeclares exceptions a method might throw

Leave a Reply