Last Updated: 06 March, 2023
In Java, the throws keyword is used in a method signature and declares which exceptions can be thrown from a method.
Exceptions can be propagated in the call stack using the throws keyword. When a method declares that it throws an exception, it is not required to handle the exception. The caller of a method that throws exceptions is required to handle the exceptions (or throw them to its caller, and so on) so that the flow of the program can be maintained.
The throws keyword allows us to declare multiple exceptions; if we are declaring multiple exceptions, each exception should be separated by a comma in the declaration.
Throws only handles checked exceptions. Unchecked exceptions don’t need to be thrown or handled explicitly in code.
Syntax:
Java throws example
Output
Division Result: 5
ArrayIndexOutOfBounds Exception thrownIndex 5 out of bounds for length 2
Java throws example
Output
Student record added successfully...
Here, the “writeStudentRecord” method throws an IOException and declares it using the throws keyword to its callers. The “main” method calls the “writeStudentRecord” method and handles the exception within a try-catch block, and prints the exception stack trace to the console.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com