Creating an OutOfRangeException in Java

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);
  
 }

}


1 comment :

  1. 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.

    For 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.

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact