Creating Custom Exception Example
This program demonstrates creating and using custom exceptions.
Problem Statement
Write a Java program that defines a custom exception InvalidInputException and uses it in validation.
Source Code
| 1 | class InvalidInputException extends Exception { |
| 2 | public InvalidInputException(String msg){ super(msg); } |
| 3 | } |
| 4 | public class CustomExceptionExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Custom Exception Example"); |
| 7 | try { |
| 8 | validateInput(-5); |
| 9 | } catch(InvalidInputException e) { |
| 10 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 11 | } |
| 12 | } |
| 13 | static void validateInput(int num) throws InvalidInputException { |
| 14 | if(num<0) throw new InvalidInputException("Negative input not allowed"); |
| 15 | else System.out.println("Eduinq Input Validated"); |
| 16 | } |
| 17 | } |
Program Output
Eduinq Custom Exception Example Eduinq Exception: Negative input not allowed
Explanation
Custom exceptions extend Exception class to define domain-specific errors. - InvalidInputException enforces input validation rules. - Catch block handles the custom exception gracefully. - This design improves clarity and error reporting. - In enterprise systems, custom exceptions provide meaningful error messages for business logic. Conclusion: Shows creation and usage of custom exceptions.