Exception handling is an important feature in Java that helps developers manage runtime errors gracefully.
Two commonly used keywords in exception handling are:
throw
throws
Although they look similar, they serve different purposes.
What is throw in Java?
The throw keyword is used to explicitly create and throw an exception from a method or block of code.
Syntax
throw new ExceptionType("Error Message");
Example
public class ThrowExample {
public static void main(String[] args) {
int marks = -10;
if (marks < 0) { throw new ArithmeticException("Marks cannot be negative"); }
System.out.println("Valid Marks"); }
Enter fullscreen mode
Exit fullscreen mode
}
Output
Exception in thread "main"
java.lang.ArithmeticException: Marks cannot be negative
Key Points of throw
Used to explicitly throw an exception.
Followed by an exception object.
Throws only one exception at a time.
Can throw both checked and unchecked exceptions.
Used inside method body.
What is throws in Java?
The throws…