【问题标题】:Is i can write two exception in one catch in Exception handling? [duplicate]我可以在异常处理中一次捕获两个异常吗? [复制]
【发布时间】:2019-09-30 11:35:34
【问题描述】:
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);
    }

}

【问题讨论】:

  • 那么问题是什么?从 Java 7 开始就可以这样做。如果您使用 Java 7 或更高版本,则不会出现编译错误
  • 你有没有试过抛出两个异常来看看它们是否被捕获?

标签: java


【解决方案1】:

我相信这就是您正在寻找的在单个 catch 块中处理两个不同的异常,它可以这样实现,希望您了解所有可能发生的已检查异常。

 catch(Exception ex){
    if(ex instanceOf InputMismatchException )
     //Do 1....
     else if(ex instanceOf ArithmeticException)
     //Do 2...
    else
     throw ex;
               }

【讨论】:

    【解决方案2】:

    你可以做到。它将捕获错误。 您可能想使用不同的 catch 块思想。 在您的程序中,当捕获 ArithmeticException 时,会向用户打印与 InputMismatchException 相同的消息。 此外,我们喜欢从更具体的异常类型转向不太具体的异常类型。

    catch(ArtithmeticException e){
    //some code
    }
    catch(Exception e){
    //some code
    }
    

    在这种情况下,我会在第一次捕获中使用 InputMismatchException,然后捕获 ArithmeticException。

    【讨论】:

    • 问题是一次使用catch块,使用两次Exception
    【解决方案3】:

    简答:是的,您可以一次捕获多个异常。

    长答案:这是从java 7 开始添加的,您可以一次捕获不同的异常,但是您应该注意异常的顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      相关资源
      最近更新 更多