1、自定义异常
问题:自定义异常的编写有何特点?自定义异常如何抛出?
//2、自定义抛出异常
class MyException extends Exception {
String id;//异常标识
public MyException(String str) {
id = str;
}
public String toString() {
return "异常:" + id;
}
}
public class Hello2 {
public static void main(String arg[]){
try {
throw new MyException("一个异常");
}catch(MyException e) {
System.out.println(e);
}
}
}
2、方法异常声明
设计一个方法求一元二次方程的根。
//2、自定义抛出异常
class MyException extends Exception {
String id;//异常标识
public MyException(String str) {
id = str;
}
public String toString() {
return "异常:" + id;
}
}
public class Hello2 {
static double[] root(double a, double b, double c) throws MyException {
double x[] = new double[2];
if(a == 0) { throw new MyException("a不能为0。");}
else {
double disc = b*b - 4*a*c;
if(disc < 0) throw new MyException("无实数解!");
x[0] = (-b + Math.sqrt(disc)) / (2*a);
x[1] = (-b - Math.sqrt(disc)) / (2*a);
return x;
}
}
public static void main(String arg[]){
try {
double x[] = root(2.0,1,3);
System.out.println("方程根为:" + x[0] + "," + x[1]);
}catch (Exception e) {
System.out.println(e);
}
}
}