throws
throws is used in a method's signature to declare that the method might produce a certain type of exception, so whoever calls that method knows they must handle it.
1. What is throws?
throws is used in a method's signature to declare that the method might produce a certain type of exception, so whoever calls that method knows they must handle it.
2. Why is it used?
It acts as a warning label on a method, telling other developers (and the compiler) that calling this method carries a risk that must be dealt with, usually with a try-catch.
3. Real-Life Example
Think of a warning label on a product box saying "May cause allergic reaction — check ingredients." It doesn't cause the reaction itself, but it warns the user in advance that there's a certain risk involved.
4. Syntax
javareturnType methodName() throws ExceptionType { // method body }
5. Example Program
javaimport java.io.IOException; public class ThrowsDemo { static void readFile() throws IOException { throw new IOException("File not found"); } public static void main(String[] args) { try { readFile(); } catch (IOException e) { System.out.println("Handled: " + e.getMessage()); } } }
Output:
Handled: File not found6. Key Points to Remember
throwsis written in the method signature;throwis used inside the method body to actually trigger an exception.- A method can declare multiple exception types using
throws, separated by commas. throwsis mainly required for checked exceptions (explained further in topic 71).