Java异常处理的学习笔记

* Java异常结构

1.Error(错误)

      Error类型异常用于 Java 运行时系统来显示与运行时与系统有关的错误。堆栈溢出是这种错误的一种。它们通常是致命性的错误,程序本身是无法控制的。

2. RuntimeException(运行时异常)

      比如:NullPointerException、IndexOutBoundsException、ArithmeticException(除数为0)、IllegalArgumentException

     这些异常不是检查异常,程序中可以选择处理捕获,也可以不处理,这种异常是可以避免的,程序员应当减少代码中的错误。

3.CheckedException(检查型异常、非运行时异常)

      从程序语法角度说必须进行处理该异常,如果不处理就无法通过编译。如:IOExeption、SQLException及用户自定义异常等。 

*try-catch异常处理

import java.util.*;
public class a { 
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        boolean cotinueInput = true;
        do {
           try {
              System.out.println("输入一个整型数据:");
              int number = scanner.nextInt(); //可以产生数据类型不一致异常
             System.out.println(" 你输入的是:" + number);
            cotinueInput = false;
          }
          catch (InputMismatchException e) {
               System.out.println("出现异常 Try again" + e.toString());
               scanner.nextLine();
         }
      }
      while (cotinueInput == true);
    }
}

     一个try可以对应多个catch语句,分别处理不同的异常。如果在try内产生异常,那么此异常对象交给Java运行系统。此时Java运行系统从上到下分别对每个catch语句处理的异常类型进行检测,直到检测到第一个类型相匹配的catch语句为止。类型匹配

      是指catch所处理的异常类型与生成的异常对象的类型完全一致,或者是生成异常对象的父类,因此,catch语句的排列顺序应该是从特殊到一般。那祖父、父、子的排序。

*try-catch嵌套

public class a {	
    public static void main(String args[]) {
		boolean tag = false;
		try {
			int a = 0; //改变值 产生不同的异常
			int b = 3 / a; //除数为0异常
			System.out.println("a = " + a);
			try { //内层try
				tag = true;
				if (a == 1) {
					a = a / (a - 1); //除数为0异常 被外层catch捕获
				}
				if (a == 2) {
					int[] c = {2};
					c[22] = 23; //数组越界异常 内层可捕获,外捕不需要捕获
				}
			}
			catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("数组越界异常");
			}
			finally {
				System.out.println("内层 都会执行");
			}

		}
		catch (Exception e) {
			if (tag) {
				System.out.print("里层try语句抛出的异常");
			}
			System.out.println("除数为0异常");
		}
		finally {
			System.out.println("外层 都会执行");
		}
	}
}
 

 

   内层如果不能捕获,则异常交给外层,外层如果不能捕获,产生错误。

*finally

无论是否有异常,都会执行finally语句块。
上例中,当a = 1 时 结果:



*throw 语句抛出异常

throw 异常对象名

public class a {	
    public static void main(String args[]) {
		boolean tag = false;
		try {
			if (tag == false) {
				throw new Exception(); //主动抛出异常
			}
		}
		catch(Exception e) {
			System.out.println("这是一个主动抛出的异常");
		}
	}
}

     throw语句通常在方法体中,如果想在上一级代码捕获处理异常,则需要在方法中用throws 关键字声明要抛出异常的类型。

*throws声明方法可能抛出的异常

public class a {	
	static void shows(String s) throws MyException {
		throw new MyException(s);
	}

 public static void main(String args[]) {
		try {
			shows("异常也"); //调用shows()方法
		}
		catch(MyException e) {
			System.out.println(e.toString());
		}
	}
}

//自定义异常类
class MyException extends Exception {
	MyException() {
		super();
	}
	MyException(String s) {
		super(s);
	}
}

你可能感兴趣的:(java,数据结构,C++,c,C#)