1.创建自定义异常类
2.方法中通过throw关键字抛出异常对象
3.使用try-catch在当前可能抛出异常的方法中捕捉并处理异常
创建自定义异常类
class MyException extends Exception{
String ex;
public MyException(String ex){
this.ex = ex;
}
public String getEx() {
return ex;
}
public void setEx(String ex) {
this.ex = ex;
}
}
方法中处理异常
public class ExTest {
public static void main(String[] args) {
try {
getNum(1,0);
}catch (MyException ex){
System.out.println(ex.getEx());
}
}
public static int getNum(int a,int b)throws MyException{
if (b==0){
throw new MyException("分母不能为0");
}
return a+b;
}
}