什么是异常
-
软件程序在运行过程中,非常可能遇到一些问题,我们叫异常,Exception
-
异常指程序运行中出现了不期而至的各种状况,如:文件找不到,非法参数等。
-
异常发生在程序运行期间,它影响了正常的程序执行流程。
异常体系机构
Java把异常当做对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类。
在Java API中已经定义了许多异常类,这些异常类分两大类,错误Error和异常Exception。
Java异常处理机制
-
抛出异常
-
捕获异常
-
异常处理五个关键字
try、catch、finally、throw、throws
public class Text { public static void main(String[] args) { int a = 1; int b = 0; try{ //try监控区域 System.out.println(a/b); }catch (Throwable e){ //catch 捕获异常 System.out.println("程序出现异常"); }finally { System.out.println("finally"); } //finally 可以不要 IO,资源,关闭! //快捷键 Ctrl+Alt+T try { new Text().test(1,0); } catch (ArithmeticException e) { e.printStackTrace(); } } //假设这个方法中,处理不了这个异常 public void test(int a,int b) throws ArithmeticException{ if(b==0){ throw new ArithmeticException();//主动抛出异常,一般在方法中使用 } } }