异常基本概念
程序运行中,有一个不可能执行的操作而导致的程序中断。
一个异常是在一个程序执行过程中出现的一个事件,他中断了正常指令的运行,
是一种阻止程序正常运行的错误
是一个特殊的对象,Exception的子类
Java中的错误
一个合理的应用程序不能截获的严重问题,比如VM的一个故障
错误也是对象,是Error的子类
异常是程序本身可以处理的,是由程序和外部环境所引起的
错误是系统本来自带的,一般无法处理也不需要程序员处理
运行时异常
都是RuntimeException 类及其子类异常,这些异常通常是免检异常,如ArithmeticException,NullPointException,IndexOutOfBoundsException
非运行时的异常
类型上都属于Exception类及其子类,需要进行处理。如: IOException,SQLException及用户自定义的异常
异常处理
步骤:
1,抛出异常:当语义限制被违反时,将会抛出(throw)异常,即产生一个异常事件,生成一个异常对象,并把它提交给一个运行系统,再由运行系统寻找相应的代码来处理异常
2,捕获异常:异常抛出后,运行时系统从生成异常对象的代码开始,眼方法的调用栈开始查找,直到找到包涵相应处理的方法代码,并把异常对象交给该方法为止
import java.util.Scanner; public class StringDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入被除数: "); int x = input.nextInt(); System.out.println("请输入除数: "); int y = input.nextInt(); //y=0会出现异常 System.out.println(divide(x,y)); } public static int divide(int x,int y) { return x/y; } } //y=0 时,抛出异常 /* Exception in thread "main" java.lang.ArithmeticException: / by zero at StringDemo.divide(StringDemo.java:14) at StringDemo.main(StringDemo.java:11) */
算术异常属于运行时异常,程序仍可运行
不可避免的异常 ,如网络中断,内存溢出,如何去处理?
处理方式:
1,使用 try...catch...finally语句处理异常
第一步用try{....}语句块选定捕获异常的范围,也就是将可能引发异常的代码包含在try语句块中
一个try语句块可以伴随一个或多个catch语句,有多个catch块,被一个处理不同的异常
finally 语句块:无论是否发生异常,都会执行
import java.util.InputMismatchException; import java.util.Scanner; public class StringDemo { public static void main(String[] args) { try { Scanner input = new Scanner(System.in); System.out.println("请输入被除数: "); int x = input.nextInt(); System.out.println("请输入除数: "); int y = input.nextInt();//y=0会出现异常 int res = 0; res=divide(x,y); System.out.println(res); }catch(ArithmeticException e){ System.out.println("除数异常"); }catch(InputMismatchException e) { System.out.println("输入异常"); }finally{
System.out.println("无论是否异常,都会执行")
} } public static int divide(int x,int y) { return x/y; } }
2,使用throws关键字传递异常
import java.io.FileInputStream; import java.io.FileNotFoundException; public class StringDemo { public static void main(String[] args) throws FileNotFoundException { testThrows(); } public static void testThrows() throws FileNotFoundException{ FileInputStream fis = new FileInputStream("test.txt"); } } //throws 异常,向上抛出,谁导致了异常,谁就要负责