首页 > 解决方案 > 如果输入不是 bigDecimal,如何抛出异常并再次扫描?

问题描述

我想扫描 bigDecimal 但如果扫描的输入不是 bigdecimal 它应该抛出一个自定义异常并再次扫描它?

我正在尝试以下代码,但无法得出结论。

代码:

import java.util.*; 
import java.io.*;

class WrongInputException extends Exception{  
 WrongInputException(String s){  
  super(s);  
 }  
}  

public class Main
{
    public static void main(String[] args)  throws WrongInputException
    {
        try 
        {
            int number;
            Scanner sc = new Scanner(System.in);
             while (!sc.hasNextBigDecimal()) 
             {
                 throw new WrongInputException("Wrong data type of input....."); 
             }
             number = sc.nextInt();
            System.out.println(number);
        } catch(NumberFormatException e) {
           System.out.println(e.getMessage());
        } 
    }
}

标签: java

解决方案


问题是你没有处理你抛出的异常

您应该添加一个 try catch 块以在 thw 内处理它,同时还添加 asc.next();以避免无限循环

 while (!sc.hasNextBigDecimal())
         {
            try {
             throw new WrongInputException("Wrong data type of input.....");

            }catch (WrongInputException e) {
                e.printStackTrace();
            }finally {
                sc.next();
            }
        }

请注意,您的 try catch 没有任何意义,因为您有异常要抛出


推荐阅读