Menu

1 / 2

throw and throws in Java

DEV Community·Harini·5 months ago
#apBmqF7M
#dev#throw#exception#throws#ioexception
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.