public class TryCatchDemo {
public static void main(String[] args) {
System.out.println("开始");
try{
String str = null;
System.out.println(str.length());
System.out.println(str.charAt(1));
}catch (NullPointerException e){
System.out.println("空指针");
}
catch (Exception e){
System.out.println("发生异常");
}
System.out.println("结束");
}
}
- try后面可以无限catch
- Exception e为所有异常,只要有异常就可以抛出,但无法确定具体异常。
- Exception要写在最后
finally
public static void main(String[] args){
try{
String str = null;
System.out.println(str.length());
}catch(StringIndexOutOfBoundsException e){
System.out.ptintln("出错了");
}finally{
System.out.println("finally执行了");
}
}
- finally基本任何情况都会执行。
JDK1.7后面的新特性
- 在异常处理结构中可以使用更简单的代码实现资源的关闭
- IO对象的close就可以自动关闭
public class AutoCloseable {
public static void main(String[] args) {
try(
FileOutputStream fos = new FileOutputStream("E:/ABC/AAA.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
){
osw.write(1);
}catch (IOException e){
System.out.println("出错了");
}
System.out.println("程序出错了");
}
}
- 异常的执行顺序
public class FinallyDemo3 {
public static void main(String[] args) {
System.out.println(test(null));
}
public static int test(String str){
try {
System.out.println("调用了test"+str);
return str.charAt(0);
}catch (NullPointerException e ){
System.out.println("出现了空指针");
return 1;
}catch (StringIndexOutOfBoundsException e){
System.out.println("出现了数组下标越界");
return 2;
}catch(Exception e){
return 3;
}finally {
System.out.println("finally执行");
}
}
}
- 异常的方法
public class ExceptionApiDemo {
public static void main(String[] args) {
System.out.println("程序开始");
try{
String str = "A";
System.out.println(str.charAt(3));
}catch (Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println("出错了");
}
}
}
- e.printStackTrace();输出堆栈异常
- e.getMessage()输出错误信息



