自定义异常类NegativeNumberException,表示对负数执行操作时出现的异常,如计算负数的平方根。该类有一个无参构造方法和一个有参构造方法,用来设置异常信息。
定义方法:public static double squareRoot(double x),求x的平方根,如果x是负数,则抛出NegativeNumberException异常,否则调用数学类中的sqrt方法返回x的平方根。
编写一个main方法,输入一个数,调用squareRoot方法,显示它的平方根或处理异常。
注意,NegativeNumberException类的定义应该这样开始:
class NegativeNumberException {
也就是说,NegativeNumberException类的class前面不要有public。
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception{ //throws Exception不要忘记了,表示有异常输出
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
double x=s.nextInt();
try {
if(x<0)
throw new NegativeNumberException("Invalid");**//抛出自定义的异常**
System.out.printf("%.2f",squareRoot(x));
}
catch(NegativeNumberException e) { *//捕获异常并输出,输出用e.getMessage(),printStackTrack()表示将堆栈的跟踪信息输出到标准流之中,printStackTrack(String s)表示将堆栈的跟踪信息通过参数s返回;*
System.out.println(e.getMessage());
}
}
public static double squareRoot(double x) {
return Math.sqrt(x);
}
}
class NegativeNumberException extends Exception{ **//自定义异常的名称以及函数体**
NegativeNumberException(){}
NegativeNumberException(String s){ **//一般都是直接构造有参函数和无参函数,然后继承即可**
super(s);
}
}