Handling Exceptions in Interface Methods
This program demonstrates handling exceptions in interface implementations.
Problem Statement
Write a Java program where interface methods declare exceptions and implementing classes handle them.
Source Code
| 1 | interface RiskyInterface { |
| 2 | void risky() throws Exception; |
| 3 | } |
| 4 | class Implementation implements RiskyInterface { |
| 5 | public void risky() throws Exception { |
| 6 | throw new Exception("Eduinq Interface Exception"); |
| 7 | } |
| 8 | } |
| 9 | public class InterfaceExceptionExample { |
| 10 | public static void main(String[] args) { |
| 11 | System.out.println("Eduinq Interface Exception Example"); |
| 12 | RiskyInterface ri=new Implementation(); |
| 13 | try { |
| 14 | ri.risky(); |
| 15 | } catch(Exception e) { |
| 16 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 17 | } |
| 18 | } |
| 19 | } |
Program Output
Eduinq Interface Exception Example Eduinq Exception: Eduinq Interface Exception
Explanation
Interfaces can declare exceptions in method signatures. - Implementing classes must honor or handle them. - Provides flexibility in contract design. - In enterprise systems, interface exception handling ensures predictable integration. Conclusion: Shows handling exceptions in interfaces.