zoukankan      html  css  js  c++  java
  • 【Java】异常 —— throw, throws, try catch 相关内容

    嗯……面试考到了这个,又是一个如无意外

    那么接下来就总结吧

     

    一、什么是异常

    程序运行过程中发生的异常事件。

     

    RuntimeException通常是因为编程员因为疏忽没有检查而引起的错误。 

    二、Exception和Error的区别

    Exception:

    1.可以是可被控制(checked)或者不可控制(unchecked);

    2.表示一个由程序员导致的错误;

    3.应该在应用程序级被处理;

     

    Error:

    1.总是不可控制的(unchecked);

    2.经常用来表示系统错误或者底层资源错误;

    3.如果可能的话,应该在系统级被捕捉;

     

    三、throw、throws、try...catch...

    ①throw

    ②throws

    ③try...catch...finally...以及语句中出现return的情况

    ④自定义异常

     

    throw是语句抛出一个异常,语法:

    throw e 

    例子:

    String a = "abcd";
    if(a.length()>5) {
      throw new NullPointerException(); //具体的异常需与方法内容相关,否则编译不通过
    }
    if(a.length()>5) {
      throw new IndexOutOfBoundsException();
    }
    if(a.length()>5) {
      //throw new IOException(); 编译不通过
    }
    

     

    throws是方法抛出一个异常,语法:

    public void doSomething() //具体方法
    throws Exception1, Exception2{}//抛出的异常
    
    //示例
    public static int calculate(int a, int b) throws ArithmeticException {
      int c = a/b;
      return c;
    }
    

     

     throw和throws的总结:

      throw throws
    定义 语句抛出异常 声明异常/方法抛出异常
    语法 throw e [方法] throws e1,e2
     位置 用于方法内  位于方法声明后 
    使用情况

    不能单独使用,

    通常与try...catch搭配使用

    能够单独使用
    编译   对方法中可能出现的异常进行捕获
    运行 抛出异常实例 只有出现异常时才抛出
         

     

    try...catch...finally

    如果以下部分中出现return,其返回结果将是如何?

    	
    public static int method(int a,int b) {
    		
      try {
        int c = a/b; //1
        return 1; //2
      } catch (Exception e) {
        System.out.println("catch"); //3
        return 2; //4
      } finally {
        System.out.println("finally"); //5
        return 3; //6
      }
    }

     

    try、catch中任一部分含有return:首先执行trycatch语句中的内容,缓存语句中return的值,最后执行finally中的内容。

    因此,

    ①当finally中return语句时,执行顺序为

    · 没有异常时:

    //执行顺序 1 → 2(缓存return的值)→5 → 6 (更改了return的值),因此打印结果为 
    finally
    3
    View Code

     · 有异常时:

    //执行顺序为:3 → 4(缓存return的值为2) → 5 → 6(更改缓存的return值为3)
    catch
    finally
    3
    View Code

    ② 当finally没有return语句时

    · 没有异常时:

    //执行顺序:1 → 2(缓存return的值)→ 5 → 返回return的值
    finally 
    1
    View Code

    · 有异常时

    //执行顺序:3 → 4(缓存return的值)→ 5 → 返回return的值
    finally 
    2
    View Code

    如果返回的不是基本数据类型,可参照这篇文章:https://blog.csdn.net/zoujian1993/article/details/45362931

    try..catch..中涉及运算:https://www.cnblogs.com/superFish2016/p/6687549.html

    涉及的堆和栈:https://blog.csdn.net/pt666/article/details/70876410/

  • 相关阅读:
    Js 之获取QueryString的几种方法
    Go语言 之md5加密
    跨域取文件(跨项目)
    System.IO
    System.Threading.Tasks
    JS存取Cookies值,附自己写的获取cookies的一个方法
    HttpServerUtility 和 HttpUyility
    JS格式化时间
    JS获取页面传过来的值
    Navigator 对象
  • 原文地址:https://www.cnblogs.com/tubybassoon/p/9678042.html
Copyright © 2011-2022 走看看