import java.io.*; public class UseMyException { public static void main(String[] args) throws MyException, IOException { int min = 10, max = 30; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Input a number between " + min + " and " + max + " included"); int value = Integer.parseInt(br.readLine()); if (value < min || value > max) throw new MyException("The value is not in the allowed interval"); System.out.println("The value is in the allowed interval"); } }
The following is an example of a run of the program:
Input a number between 10 and 30 included 9 Exception in thread "main" MyException: The value is not in the allowed interval at UseMyException.main(UseMyException.java:11)
Note: If we had defined the class MyException as a subclass of RuntimeException, instead of Exception, then we could have avoided to indicate MyException in the throws clause of the definition of the main() method.