如何捕获算术异常

Pro*_*345 1 java exception-handling

我试图通过使用try catch块或抛出异常方法来捕获以下代码中的异常.我已尝试使用try catch块并在代码中的不同位置抛出异常方法但我仍然无法捕获异常

package thowsexception;

import java.io.IOException;
import java.rmi.AccessException;

public class IOexception {
    public  int example1(int i, int j) throws ArithmeticException {
    int k ;

        if (i == 0){
            throw new ArithmeticException("cannot Divide By 0");
        }
        return  i /j ;

//        try {
//          
//        k  =  i/j ;
//        }
//        
//        catch (ArithmeticException e){
//          
//          System.out.println("Error: Don't divide a number by zero");
//        }



    }
}
Run Code Online (Sandbox Code Playgroud)

主类

package thowsexception;

import java.io.IOException;

public class IOexception {

    public static void main(String[] args) throws ArithmeticException {
        example e = new example();
        e.example1(5,0);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ahm*_*rdi 6

您可以通过不同方式解决此问题

public int example1(int i, int j) throws ArithmeticException {


    if (j == 0) {// you should check j instead of i
        throw new ArithmeticException("cannot Divide By 0");
    }

        return i / j;
}
Run Code Online (Sandbox Code Playgroud)

要么

public int example1(int i, int j) throws ArithmeticException {

    try {
        return i / j;
    }
    catch (ArithmeticException e) {
        throw new  ArithmeticException("Error: Don't divide a number by zero");
    }
}
Run Code Online (Sandbox Code Playgroud)

但第一个是正确的超过秒,因为未经检查的扩展代表编程错误,编程错误应该是固定的,并且大多数时候这些异常是由于用户在用户程序交互期间提供的错误数据而发生的,所以我们应该防止这些类型错误而不是抓住它.

阅读更多关于更好地了解on-checked-vs-unchecked-exceptions-how-to-handle-exception-better-way-in-java