essage() : 打印异常信息 ; b、printStackTrace() : 打印整个堆栈信息
5、在try结构中声明的变量,在出了try结构以后,就不能够再被调用(类似局部变量)。
finally的使用:
1、finally 是可选的
2、finally中声明的是一定会被执行的代码。即使catch中又出现了异常,try中有return语句,catch中有return语句等情况(finally先于try和catch中的return语句)。
3、像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中。
try-catch-finally的使用:
1、try-catch-finally可以相互嵌套
体会1:当我们使用try-catch处理编译时异常,使得我们程序在编译时不报错,但在运行时,仍可能报错,相当于,我们使用哦try-catch-finally讲一个编译时出现的异常,延迟到运行时出现。
体会2:由于开发中,运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally。然后针对于编译时异常,我们说一定要考虑异常的处理。
*/
4、异常处理机制二:throws
4.1 throws说明:
package ExceptionTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
* 异常处理方式二:throws + 异常类型
*
* 1."throws + 异常类型" 写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。
* 一旦方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,
* 就会被抛出。异常代码后续的代码就不再执行。
*
* 2.体会:try-catch-finally:真正的将异常给处掉了
* throws的方式只是将异常抛给了方法的调用者。并没有真正将异常处理掉。
*
* 3.
*/
public class throwsTest {
public static void main(String[] args){
try{
method2();
}catch(IOException e){
e.getStackTrace();
}
}
public static void method2() throws IOException{
method1();
}
public static void method1() throws FileNotFoundException,IOException{
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.println((char)data);
data = fis.read();
}
fis.close();
}
}
4.2 方法重写:
package ExceptionTest;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
* 方法重写:
* 规则一:子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型(对于多态会出问题)。
*
*/
public class OverrideTest {
public static void main(String[] args) {
OverrideTest o = new OverrideTest();
o.display(new SubClass());
}
public void display(SuperClass s){
try{
s.method();
}catch(IOException e){
e.printStackTrace();
}
}
}
class SuperClass{
public void method() throws IOException{
}
}
class SubClass extends SuperClass{
public void method()throws FileNotFoundException{
}
}
5、手动抛出异常:throw
package ExceptionTest;
import javax.management.RuntimeErrorException;
public class StudentTest {
public static void main(String[] args) {
try {
Student s = new Student();
s.regist(-101);
System.out.println(s);
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
class Student{
private int id;
public void regist(int id) throws Exception{
if(id > 0)this.id = id;
else {
//System.out.println("您输入数据有误!");
//手动抛出一个异常对象
//运行时错误,不能处理
//throw new RuntimeException("您输入的数据非法");
//编译时异常,需要处理
throw new Exception("您输入的数据非法");
}
}
@Override
public String toString() {
return "Student [id=" + id + "]";
}
}
6、用户自定义异常类
package ExceptionTest;
/*
* 如何自定义异常类:
* 1.继承于现有的异常结构:RuntimeException(运行时异常,不用显示处理)、Exception(需要显示处理)
* 2.提供一个serialVersionUID(全局常量),序列号去表示该类
* 3.提供几个重载的构造器
*
*/
public class MyException extends RuntimeException{
static final long serialVersion