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)
我一直想不明白,求解答。
不好意思“调用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方法。
我虽然是小白但是姑且说一下我的想法哈~这个意思应该是说在main里面调用的divide方法可能会抛出异常,但是你没有写抛出了异常之后要如何处理的方法,也就是没有写try-catch,所以如果main写成
public static void main(String[] args) {
try {
Merry.divide(10, 0);
}catch(Exception e) {
System.out.println("除数不能为零");
}
}
应该就可以了。
不过我还不太清楚Exception(“除数不能为零”)这里面的字符串参数有什么用,望交流指点呀!~
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));
	}Unhandled exception type Exception
也就时在主方法调用那一行