首先,我想说通过使用if-else配置或while循环,我知道这个程序可以更容易完成,但我想知道如何使用异常类来完成它。 (我猜我需要使用try-catch块来定制异常)。
import java.util.Scanner;
class AgeChecker
{
public static void main(String [] args)
{
Scanner inputdata = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = inputdata.nextLine();
System.out.print(name+", enter your age: ");
int age = inputdata.nextInt();
try
{ // age entered must be between 0-125 (how to trigger exception in catch block?)
System.out.println("You entered: "+age);
}
catch(Exception e)
{
System.out.println("Out of range error! (must be between ages 0 and 125)"+e);
}
finally
{
System.out.println("Age Checking Complete.");
}
}
}
答案 0 :(得分:1)
虽然我不确定为什么不使用if-else而不是异常,但您可以通过继承现有异常类来创建自定义异常。通常,您将为“声明的”异常子类化Exception,并为您不希望捕获的异常创建RuntimeException。在你的情况下,你可以只是子类Exception,如:
public MyException extends Exception
{
}
然后在发现范围问题时抛出它:
throw new MyException();
然后通过捕获异常来捕获它,就像你做的那样或MyException:
catch(MyException exp) ...
答案 1 :(得分:1)
package example.stackoverflow;
import java.util.Scanner;
public class AgeChecker
{
public static final int MIN_AGE = 0;
public static final int MAX_AGE = 125;
static class InvalidAgeException extends Exception
{
private static final long serialVersionUID = 1340715735048104509L;
public InvalidAgeException()
{ }
public InvalidAgeException(String message)
{
super(message);
}
public InvalidAgeException(String message, Throwable cause)
{
super(message, cause);
}
}
public static void main(String[] args)
{
Scanner inputdata = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = inputdata.nextLine();
System.out.print(name+", enter your age: ");
int age = inputdata.nextInt();
try
{
System.out.println("You entered: "+age);
// Assuming age limits are non-inclusive
if( (age <= MIN_AGE) || (age >= MAX_AGE) )
{
throw new InvalidAgeException("Out of range error! (must be between ages 0 and 125)");
}
}
catch(InvalidAgeException e)
{
e.printStackTrace();
}
finally
{
System.out.println("Age Checking Complete.");
if(inputdata != null)
{
inputdata.close();
}
}
}
}
另请注意,只要完成扫描仪,就需要关闭()扫描仪。在finally块中进行这样的清理通常很有用,所以我把它放在这个例子中。
答案 2 :(得分:0)
您可以创建自己的Exception
实例。如果您想触发catch
阻止,则需要throw
中的Exception
try
:
try {
System.out.println("Enter your age: ");
int age = scanner.nextInt();
if(isInvalid(age)) {
throw new Exception("Age is invalid!");
}
} catch (Exception e) {
// etc
}
您可能还需要考虑subclassing Exception
提供一些bit more information来解决导致问题的原因。
答案 3 :(得分:0)
public class yourExcetionActivity extends Exception
{
public yourExcetionActivity() { }
public yourExcetionActivity(String string) {
super(string);
}
}