Declaring Exceptions with Throws
This program demonstrates the use of throws keyword.
Problem Statement
Write a Java program that declares exceptions using throws.
Source Code
| 1 | public class ThrowsKeywordExample { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Throws Keyword Example"); |
| 4 | try { |
| 5 | riskyMethod(); |
| 6 | } catch(Exception e) { |
| 7 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 8 | } |
| 9 | } |
| 10 | static void riskyMethod() throws Exception { |
| 11 | throw new Exception("Eduinq Risky Operation Failed"); |
| 12 | } |
| 13 | } |
Program Output
Eduinq Throws Keyword Example Eduinq Exception: Eduinq Risky Operation Failed
Explanation
The throws keyword declares exceptions that may be thrown by a method. - It informs the caller to handle or propagate the exception. - This design improves clarity and error management. - Declaring exceptions ensures predictable program behavior. - In enterprise systems, throws keyword improves contract enforcement between methods. Conclusion: Shows declaring exceptions using throws keyword.