59.异常
抓抛模型:
抛出:出现异常,会生成一个对应异常类的对象。
并将此对象抛出。
一旦抛出异常之后,其后代码不再执行。
抓:异常处理方式,第一种try-catch-finally,第二种throws
try-catch-finally的使用
try{
//可能出现的异常
}catch(异常类型1 变量名1){
//异常处理方式1
}catch(异常类型2 变量名2){
//异常处理方式2
}
...
finally{//一定会执行的代码}
//案例
@Test
public void test1()
{
String str="123";
str="abc";
try{
int num=Integer.parseInt(str);
}catch(NumberFormatException e)
{
System.out.println("数值异常");
}
System.out.println("还是会继续执行这个语句,因为异常已经被处理");
}
使用try-catch相当于把编译时的异常延迟到运行时出错。
finally是可选的,但是只要写了finally,里面的内容一定会被执行!!无论什么情况。使用情况:数据库连接,输入输出流,Socket关闭,JVM不能自动回收。
throws异常处理方法:把异常向上抛
写在方法的声明处,指明此方法执行时,可能会抛出的异常类型。一旦方法执行,出现异常仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会抛出。
throws是处理异常的方法,throw是生成一个异常对象并且抛出
public class StudentTest {
public static void main(String[] args) {
try {
Student s=new Student();
s.resgist(-1001);
System.out.println(s.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
class Student
{
private int id;
public void resgist(int id) throws Exception
{
if(id>0)
this.id=id;
else
{
//手动抛出异常
//System.out.println("errorinput");
throw new Exception("errorinput");
}
}
@Override
public String toString() {
return "Student [id=" + id + "]";
}
}
用户自定义异常