异常处理
异常的分类:可查异常,运行时异常和错误
不处理异常后面代码是不会被执行的
try{
}catch(){
}
try{
}catch(){
}catch(){
}
finally关键字
用于表示一个代码块,特点:无论如何最终都会执行finally语句,目的:是释放资源
异常的抛出 throw和throws
throw在方法内部抛出一个异常对象
public class throwDemo { public static void main(String[] args) { chu(3,0); } public static int chu(int a,int b){ if(b==0){ throw new ArithmeticException("除数不能为0"); } return a/b; } }
throws在方法声明上,抛出一个异常类型(我不想处理交给调用我的方法吧)
这种情况处理方式有两种1,try catch在调用者的方法里结束掉.2,继续抛出给上层.
自定义异常类
public class LoginException extends RuntimeException{ public LoginException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public LoginException(String message) { super(message); // TODO Auto-generated constructor stub } }
public class Login { public static void main(String[] args) { login("tom"); } public static void login(String str){ String[] names = {"will","jack","tom"}; for (String name : names) { if(name == str){ throw new LoginException("用户名存在"); } } } }