栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA中的异常

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA中的异常

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("程序出错了");
    }
}
  1. 异常的执行顺序
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执行");
       }

    }
}

  1. 异常的方法
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()输出错误信息
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/340672.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号