DEV Community

rajeshwari rajeshwari
rajeshwari rajeshwari

Posted on

in java throw,what,why?

In Java, throw is a keyword used to explicitly throw an exception. Here's a breakdown of the what, why, how, and when to use it:


๐Ÿ”น What is throw in Java?

  • throw is used to manually trigger an exception during program execution.
  • It transfers control from the current block of code to the nearest catch block that can handle the exception.
throw new IllegalArgumentException("Invalid input");
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Why use throw?

You use throw to:

  • Handle unexpected situations or errors in your code.
  • Validate input (e.g., null values, invalid arguments).
  • Provide custom error messages or throw custom exceptions.
  • Improve code robustness by catching problems early.

๐Ÿ”น How to use throw in Java?

โœ… Syntax:

throw new ExceptionType("Error message");
Enter fullscreen mode Exit fullscreen mode

โœ… Example:

public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}
Enter fullscreen mode Exit fullscreen mode

Note: The object thrown must be of type Throwable (i.e., Exception or subclass).

โœ… Custom Exception Example:

class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

public void checkSomething(boolean condition) throws MyException {
    if (!condition) {
        throw new MyException("Condition failed");
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น When to use throw in Java?

Use throw when:

  • You need to stop normal flow due to a problem.
  • Input is invalid or violates rules.
  • Something unexpected happens (e.g., file not found, null value).
  • You are implementing custom business logic exceptions.

โš ๏ธ Common Mistakes

  • Forgetting new when creating the exception:
  throw IllegalArgumentException("error"); // โŒ wrong
  throw new IllegalArgumentException("error"); // โœ… correct
Enter fullscreen mode Exit fullscreen mode
  • Throwing a non-Throwable type:
  throw "error"; // โŒ wrong
Enter fullscreen mode Exit fullscreen mode
  • Forgetting to declare or handle checked exceptions:
  public void riskyMethod() throws IOException {
      throw new IOException("Disk not found"); // must declare or handle
  }
Enter fullscreen mode Exit fullscreen mode

Would you like an explanation of the difference between throw and throws too?

Top comments (0)