Description:
In this java code, we create an OutOfRangeException; and then we test it.
Code:
package com.javaproblems.creatingexceptions;
import java.util.Scanner;
public class CreatingExceptions {
public static void main(String[] args) throws OutOfRangeException {
Scanner scan = new Scanner(System.in);
int val;
final int MIN = 0, MAX = 100;
OutOfRangeException problem =
new OutOfRangeException("Input value is not valid");
System.out.println("Enter an int value between " +
MIN + " and " + MAX);
val = scan.nextInt();
if (val<MIN || val > MAX) {
throw problem;
}
}
}
package com.javaproblems.creatingexceptions;
public class OutOfRangeException extends Exception{
public OutOfRangeException(String msg) {
super(msg);
}
}
Creating a custom exception in Java is a useful way to handle application-specific validation errors. This example demonstrates how to define an `OutOfRangeException` by extending Java's `Exception` class, pass an error message through its constructor, and throw the exception when an input value falls outside the permitted range. Understanding custom exceptions helps developers write more structured and maintainable Java applications.
ReplyDeleteFor students looking to strengthen their Java programming knowledge, the Java Full Stack Developer Course provides a pathway to explore core programming concepts and apply them in practical application development.