Handling Exceptions in Constructors
This program demonstrates handling exceptions in constructors.
Problem Statement
Write a Java program where constructor throws exception and is handled in main.
Source Code
| 1 | class RiskyConstructor { |
| 2 | public RiskyConstructor() throws Exception { |
| 3 | throw new Exception("Eduinq Constructor Exception"); |
| 4 | } |
| 5 | } |
| 6 | public class ConstructorExceptionExample { |
| 7 | public static void main(String[] args) { |
| 8 | System.out.println("Eduinq Constructor Exception Example"); |
| 9 | try { |
| 10 | RiskyConstructor rc=new RiskyConstructor(); |
| 11 | } catch(Exception e) { |
| 12 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 13 | } |
| 14 | } |
| 15 | } |
Program Output
Eduinq Constructor Exception Example Eduinq Exception: Eduinq Constructor Exception
Explanation
Constructors can throw exceptions during object creation. - Caller must handle exceptions to prevent program crash. - Improves reliability and error reporting. - In enterprise systems, constructor exception handling ensures safe initialization. Conclusion: Shows handling exceptions in constructors.