1.异常处理
(1)java异常处理机制
- java中所有错误的超类为:Throwable。其下有两个子类:Error和Exception
- Error的子类描述的都是系统错误,比如虚拟机内存溢出等。
- Exception的子类描述的都是程序错误,比如空指针,下表越界等。
- 通常我们程序中处理的异常都是Exception。
(2)异常处理机制中的try-catch
package exception;
public class TryCatchDemo {
public static void main(String[] args) {
System.out.println("程序开始了");
try {
String line = "abc";
System.out.println(line.length());
System.out.println(line.charAt(0));
System.out.println(Integer.parseInt(line));
System.out.println("!!!!!!!!!!!!!!!!");
}catch(NullPointerException|StringIndexOutOfBoundsException e){
System.out.println("出现了空指针或下标越界并处理了!");
}catch(Exception e){
System.out.println("反正就是出了个错");
}
System.out.println("程序结束了");
}
}
`
#### 异常处理机制中的finally
- finally块定义在异常处理机制中的最后一块。它可以直接跟在try之后,或者最后一个catch之后。
- finally可以保证只要程序执行到了try语句块中,无论try语句块中的代码是否出现异常,最终finally都必定执行。
- finally通常用来做释放资源这类操作。
```java
package exception;
public class FinallyDemo {
public static void main(String[] args) {
System.out.println("程序开始了...");
try{
String line = "abc";
System.out.println(line.length());
return;
}catch(Exception e){
System.out.println("出错了!");
}finally{
System.out.println("finally中的代码执行了!");
}
System.out.println("程序结束了!");
}
}
(3)IO操作时的异常处理机制应用
package exception;
import java.io.FileOutputStream;
import java.io.IOException;
public class FinallyDemo2 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("fos.dat");
fos.write(1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos!=null)