int c = a/b; 这个位置应该放在 if(b==0) 里面,你写 if(c==0) 是指商等于0的情况执行掏出一个Exception异常,而实际上,你b=0,在执行 c=a/b 时就产生异常了,异常信息就是 被除数不能为0,
说错了,是if(b!=0)
public class test3 { public static void main(String[] args) { // TODO Auto-generated method stub test3 ff=new test3(); try { ff.add(5, 0); } catch (Exception e) { // TODO Auto-generated catch block System.out.println(e.getMessage()); } }
public void add(int a, int b)throws Exception{ if(b==0) { throw new Exception("除数不能为0!"); }else { System.out.println(a/b); } }}
public class Test { private int a; private int b; public Test(int a, int b){ this.a = a; this.b = b; } public int division()throws Exception{ if (b == 0) { throw new Exception("除数不能为0!"); } else { int resultNum = a/b; return resultNum; } } public static void main(String[] args) { Test test = new Test(1,5); try{ System.out.println(test.division()); }catch(Exception e){ e.getMessage(); } } }
// TODO Auto-generated method stub
test3 ff=new test3();
try {
ff.add(5, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
} }
public void add(int a, int b)throws Exception{
if(b==0) {
throw new Exception("除数不能为0!");
}else {
System.out.println(a/b);
}
}}
private int a;
private int b; public Test(int a, int b){
this.a = a;
this.b = b;
} public int division()throws Exception{
if (b == 0) {
throw new Exception("除数不能为0!");
} else {
int resultNum = a/b;
return resultNum;
}
} public static void main(String[] args) {
Test test = new Test(1,5);
try{
System.out.println(test.division());
}catch(Exception e){
e.getMessage();
}
}
}