问答详情
源自:1-7 Java 中的异常链

为什么会报错呢?怎么处理呢?

package qqq;


public class Merry {



public   static void   divide(int a,int b)throws Exception{

if (b==0) {

throw new Exception("除数不能为零");

}

else{System.out.println("两数相除,商为:"+a/b);}

}


public static void main(String[] args) {

// Merry merry=new Merry();

Merry.divide(10, 2);

}


}

然后运行的结果是:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

Unhandled exception type Exception


at qqq.Merry.main(Merry.java:17)

我一直想不明白,求解答。

提问者:滴滴滴滴滴 2017-07-26 17:42

个回答

  • 慕盖茨7528959
    2017-07-27 13:24:20
    已采纳

    不好意思“调用e.方法”能不能详细说说……(我是真的小白

    嗯可是我觉得,就目前来看这个divide方法只负责抛出异常,本身没有处理异常的功能。不知道你的想法是不是下面这样:

    public void test(int a,int b) {
          try {
               Merry.divide(a, b);
          }catch(Exception e) {
               System.out.println("除数不能为零");
          }
     }
     
     public static void main(String[] args) {
          Merry merry=new Merry();
          merry.test(10, 2);
     }

    就是再写一个带参的test方法,这个方法调用divide方法,并且可以解决它抛出的异常,然后main直接调用test方法。

  • 慕盖茨7528959
    2017-07-27 10:17:53

    我虽然是小白但是姑且说一下我的想法哈~这个意思应该是说在main里面调用的divide方法可能会抛出异常,但是你没有写抛出了异常之后要如何处理的方法,也就是没有写try-catch,所以如果main写成

    public static void main(String[] args) {

        try {

            Merry.divide(10, 0);

        }catch(Exception e) {

            System.out.println("除数不能为零");

    }

    }

    应该就可以了。

    不过我还不太清楚Exception(“除数不能为零”)这里面的字符串参数有什么用,望交流指点呀!~


  • _泥人_
    2017-07-26 18:57:54

    public static void  ivide(int a,int b)throws Exception{
        if (b==0) {
            throw new Exception("除数不能为零");
        }
        else{
            System.out.println("两数相除,商为:"+a/b);}
            throw new Exception();
        }
    
    public static void main(String[] args) {
        divide(10, 2);
    }

    b==0 ? 不等于零你是要抛出异常的。  你想要捕获异常,然后输出中文的异常,不是这么搞的。

    public static double divide(int a, int b){
    		try {
    			return a/b;
    		} catch (Exception e) {
    			if(b == 0){
    				System.out.println("除数不能为零!");
    			}else{
    				e.printStackTrace();
    			}
    			return 0D;	
    		}
    	}
    	
    	public static void main(String[] args) throws Exception {
    		
    		System.out.println(divide(10, 2));
    	}


  • qq_makesprefect_0
    2017-07-26 17:57:14

    Unhandled exception type Exception

  • 滴滴滴滴滴
    2017-07-26 17:49:58

    也就时在主方法调用那一行