异常
异常是导致程序中断运行的一种指令流。

举例:10÷0
1 package com.feimao.a1;
2
3 public class ExceptionDemo01 {
4 public static void main(String args[]){
5 System.out.println("************程序开始*****************");
6 int i = 10;
7 int j = 0;
8 try {
9 int temp = i / j;
10 System.out.println("两个数字i除以j的结果:" + temp);
11 }catch (ArithmeticException e){
12 System.out.println("捕捉异常" + e);
13 }
14 System.out.println("************计算结束***************");
15
16 }
17 }
当try代码块内的语句发生异常,其下面的所有语句将不再执行。跳转到相应的catch中捕获异常。对于异常可以统一使用finally作为统一出口。
举例:finally
1 package com.feimao.a1;
2
3
4
5 public class ExceptionDemo01 {
6
7 public static void main(String args[]){
8
9 System.out.println("************程序开始*****************");
10
11 int i = 10;
12
13 int j = 2;
14
15 try {
16
17 int temp = i / j;
18
19 System.out.println("两个数字i除以j的结果:" + temp);
20
21 }catch (ArithmeticException e){
22
23 System.out.println("捕捉异常" + e);
24
25 }finally {
26
27 System.out.println("不管有没有发生异常,都会执行此代码");
28
29 }
30
31 System.out.println("************计算结束***************");
32
33
34
35 }
36
37 }
异常类的继承机构:
在整个java异常结构中,实际上有两个最常用的类exception 和 error这两个类都是throwable的子类
Exception是指程序中出现的异常,可以直接用try ……catch捕获
Errory一般是指jvm错误,程序无法处理
异常
异常是导致程序中断运行的一种指令流。
Throw和throws关键字
定义一个方法的时候可以使用throws关键字声明,使用throws方法的时候表示此方法不处理异常,但是交给方法的调用处处理。
而throw只是抛出异常对象。
格式:public 返回值类型 方法名称(方法参数) throws异常类{}
举例:throws抛出异常
1 package com.feimao.a1;
2
3
4
5 class Math{
6
7 public int div(int i , int j) throws Exception{
8
9 int temp = i / j;
10
11 return temp;
12
13 }
14
15 }
16
17 public class ExceptionDemo01 {
18
19 public static void main(String args[]){
20
21 Math m = new Math();
22
23 try {
24
25 System.out.println("两个数字相除的结果:" + m.div(10 , 2));
26
27 }catch (Exception e){
28
29 e.printStackTrace();
30
31 }
32
33 }
34
35 }
36
来源:https://www.cnblogs.com/feimaoyuzhubaobao/p/9859330.html