猿问

我是否可以在异常处理中的一个catch中编写两个异常?[重复]

package dividedbyzero;import java.util.InputMismatchException;import java.util.Scanner;/**
 *
 * @author HP
 */public class Dividedbyzero {

    public static int quo(int num,int denum)
            throws ArithmeticException
    {
        return num/denum;
    }
    public static void main(String[] args) {
       Scanner obj=new Scanner(System.in);
       boolean conlop=true;
       do{
           try{
               System.out.print("please enter integer");
               int num=obj.nextInt();
               System.out.print("please inter");
               int denum=obj.nextInt();

               int result=quo(num,denum);
               System.out.printf("%nRESULT : %d /%d = %d%n",num,denum,result);
               conlop=false;

           }
           catch(InputMismatchException   | ArithmeticException a){
               System.err.printf("%n Exception : %s%n",a);
               obj.nextLine();
               System.out.printf("you mustt num please enter again");
           }

       }while(conlop);
    }}


哈士奇WWW
浏览 1204回答 3
3回答

神不在的星期二

简短回答:是的,您可以在一个捕获中捕获多个异常。答案很长:这是从java 7开始添加的,你可以在一个catch 中添加不同的异常,但是你应该注意异常的顺序。

慕妹3242003

我相信你正在寻找在单个catch块中处理两个不同异常的东西,它可以像这样实现,希望你知道可能发生的所有已检查异常。 catch(Exception ex){     if(ex instanceOf InputMismatchException )      //Do 1....      else if(ex instanceOf ArithmeticException)      //Do 2...     else      throw ex;                }

德玛西亚99

你能行的。它会捕获错误。您可能想要使用不同的catch块。在您的程序中,当捕获ArithmeticException时,将向InputMismatchException输出与用户相同的消息。此外,我们希望从更具体的异常类型转变为不太具体的异常类型。catch(ArtithmeticException e){//some code}catch(Exception e){//some code}在这种情况下,我会在第一个catch中使用InputMismatchException,然后捕获ArithmeticException。
随时随地看视频慕课网APP

相关分类

Java
我要回答