【Java】异常 —— throw, throws, try catch 相关内容

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

那么接下来就总结吧java

 

1、什么是异常程序员

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

 

RuntimeException一般是由于编程员由于疏忽没有检查而引发的错误。 编程

 

2、Exception和Error的区别缓存

Exception:ide

1.能够是可被控制(checked)或者不可控制(unchecked);spa

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

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

 

Error:

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

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

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

 

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:首先执行try\catch语句中的内容,缓存语句中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..中涉及运算:http://www.javashuo.com/article/p-yowfqdjg-a.html

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

相关文章
相关标签/搜索