常见异常:
自定义异常:
案例:
public class MyException extends Exception{
String errorMessage;
public MyException(String errorMessage) {
super(errorMessage);
this.errorMessage=errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
}
public class ExceptionTest {
public static double div(double a,double b) throws MyException
{
if(b<=0)
{
throw new MyException("除数不能为0");
}
return a/b;
}
public static void main(String args[])
{
try {
double result=ExceptionTest.div(2,0);
} catch (MyException e) {
System.out.println(e.getErrorMessage());
}
}
}
输出结果: