[手动引发异常时,您可以发送一条小消息:
throw new Exception("this message");
但是在运行此代码时,我必须输入浮点数,因此,例如,如果输入字符串,则代码本身会引发异常,但是如何发送相同类型的消息?
public class Main {
public static void main(String[] args) {
Scanner scan;
float feeHold;
System.out.println("\nEnter Registration Fee (only numbers)");
try {
scan = new Scanner(System.in);
feeHold = scan.nextFloat();
System.out.println("\n" + feeHold);
}
catch (InputMismatchException e) {
e.printStackTrace();
}
}
}
喜欢这个:
直接,您可以通过将异常代码包装到新的try-catch
块中并从catch
抛出新的自定义异常来执行此操作,但是此代码闻起来确实很不好,而且,您不应这样做,因为库/ SDK供应商想要抛出确切的异常。但是,如果您要打印自己的消息,则可以通过在catch子句中调用System.out.println("your own message")
来发送消息。
您可以按照正确的方式捕获InputMismatchException
,但是可以用自定义消息抛出新的Exception,而不是调用e.printStackTrace()
。请记住,您还需要声明main
可能会引发异常。
public class Main {
public static void main(String[] args) throws Exception {
Scanner scan;
float feeHold;
System.out.println("\nEnter Registration Fee (only numbers)");
try {
scan = new Scanner(System.in);
feeHold = scan.nextFloat();
System.out.println("\n" + feeHold);
} catch (InputMismatchException e) {
throw new Exception("Here's your custom message");
}
}
}
输出:
Enter Registration Fee (only numbers)
abc
Exception in thread "main" java.lang.Exception: Here's your custom message
at Main.main(Main.java:19)
这只是按照您的要求做的一种方法,可能不是最合适的。仔细研究一下Exception documentation,您一定会找到一种更有条理,更优雅的方式来完成任务。