JAVA抛出异常 请教

来源:百度知道 编辑:UC知道 时间:2024/07/07 01:03:24
二、创建一个Example类,该类有一个result() 方法,在result()方法内部有两个多项式A=4x-4 、 B=2*x*x-4*x*y+y*y;C=A/B ,最后返回C的值
要求:x和y的值作为该方法的形参,在计算C值以前,先判断A和B的值,当A或B等于零时抛出一个ArithmeticException异常,使用ArithmeticException捕获该异常,在创建ArithmeticException异常时须使用其带形参的构造函数,给形参赋值为“A 或 B =0”,使用getMessage()显示该字符串。
当A、B都不等于零时抛出一个Exception异常,使用Exception捕获该异常,在创建Exception异常时也须使用其带形参的构造函数,给形参赋值为“program is ok!”,使用getMessage()显示该字符串
最后不管A、B是否等于零,都须显示”program is end”(注:使用finally)
为这个类创建一个main()方法,生成两个20以内的整形随机数,调用result()方法,将这两个随机数赋给x和y.,显示最后结果。

import java.util.Random;

public class Example {

private static final long serialVersionUID = 1L;
int A;
int B;
public int result(int x,int y){

try{
A = 4*x-4;
B = 2*x*x-4*x*y+y*y;
if(A==0||B==0){
throw new ArithmeticException("A or B ==0");
}else{
throw new Exception("program is ok");
}
}catch(ArithmeticException e){
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
finally{
System.out.println("program is end");
}
int C = A/B;

return C;
}

public static void main(String[] args) {
Example example = new Example();
Random ran = new Random();
int x = ran.nextInt(20);
int y = ran.nextInt(20);
System.out.println(x);
System.out.println(y);
int C = example.result(x, y);
System.out.println(C)