Java 中的异常分类和处理方式

862 阅读3分钟

Java异常

异常本质上是程序上的错误,包括编译期间的错误和运行期间的错误

编译期间的错误有括号没有正确配对、少写分号、关键字编写错误

运行期间的错误有使用空的对象引用调用方法、数组下标越界、除数为0、类型转换时无法正常转型

异常分类

Throwable

Java中的异常由Throwable及其子类来描述。

Error

系统的内部错误和资源耗尽错误

  • JVM 内存资源耗尽时出现的 OutOfMemoryError
  • 栈溢出时出现的 StackOverFlowError
  • 类定义错误 NoClassDefFoundError

这些错误发生于虚拟机自身、或者发生在虚拟机试图执行应用时,它们在应用程序的控制和处理能力之外,一旦发生,Java 虚拟机一般会选择线程终止。

Exception

出现在程序本身,可以处理

检查异常(Checked Exception )和非检查异常(Unchecked Exception)

Java 语言规范将派生于 Error 类或 RuntimeException 类之外的所有异常都归类为可检查异常,Java 编译器会检查它,如果不做处理,无法通过编译。

RuntimeException

包括空指针异常(NullPointException)、数组下标越界异常(ArrayIndexOutOfBoundsException)、算数异常(ArithmeticException)和类型转换异常(ClassCastException)

IO异常(IOException)

SQL异常(SQLEXception)

异常处理

抛出异常+捕获异常

五个关键字:try、catch、finally、throw、throws

try...catch、try...catch...finally、try...finally

throw抛出异常对象的处理方案:

  1. 通过try...catch包含throw语句--自己抛自己处理
try{
        可能会发生的异常
    }catch(异常类型 异常名(变量)){
        针对异常进行处理的代码
    }catch(异常类型 异常名(变量)){
        针对异常进行处理的代码
    }...
    [finally{        释放资源代码;    }]

例:

public class TryDemoTwo {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int result=test();
		System.out.println("one和two的商是:"+ result);
	}
	public static int test(){
		Scanner input=new Scanner(System.in);
		System.out.println("=====运算开始=====");
		try{
			System.out.print("请输入第一个整数:");
			int one=input.nextInt();
			System.out.print("请输入第二个整数:");
			int two=input.nextInt();
			return one/two;
		}catch(ArithmeticException e){
			System.out.println("除数不允许为零");
			return 0;
		}finally{
			System.out.println("=====运算结束=====");
		//	return -100000;
		}
	}
}

注意:

  • catch 不能独立于 try 存在。
  • catch里面不能没有内容
  • 在 try/catch 后面添加 finally 块并非强制性要求的。
  • try 代码后不能既没 catch 块也没 finally 块。
  • try里面越少越好。
  • try, catch, finally 块之间不能添加任何代码。
  • finally里面的代码最终一定会执行(除了JVM退出)
  • 如果程序可能存在多个异常,需要多个catch进行捕获。
  • 异常如果是同级关系,catch谁前谁后没有关系 如果异常之间存在上下级关系,上级需要放在后面
  1. 通过throws在方法声明出抛出异常类型--谁调用谁处理--调用者可以自己处理,也可以继续上抛。此时可以抛出与throw对象相同的类型或者父类,不能是子类
public static void main(String[] args) {
		try{
			int result = test();
			System.out.println("one和two的商是:" + result);
		}catch(ArithmeticException e){
			
		}catch(InputMismatchException e){
			
		}catch(Exception e){
			
		}
		int result2=test();
	}
public static int test() throws ArithmeticException,InputMismatchException{
		Scanner input = new Scanner(System.in);
		System.out.println("=====运算开始=====");
		System.out.print("请输入第一个整数:");
		int one = input.nextInt();
		System.out.print("请输入第二个整数:");
		int two = input.nextInt();
		System.out.println("=====运算结束=====");
		return one / two;
	}

Java 中异常捕获和处理 blog.csdn.net/sugar_no1/a…