异常在java中的应用
这篇文章将为大家详细讲解有关异常在java中的应用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
一、什么是异常
异常就是程序运行过程中所出现的不正常现象。
try
:把可能发生异常的代码包起来,当发生异常时,将异常抛出
catch
:捕获异常并处理
finally
:不管是否发生异常,都会执行
throw
:手动引发一个异常
throws
:定义任何被调用方法的异常
二、异常出现的原因
用户输入错误;
代码的错误;
环境的因素;
异常机制保证了程序的健壮性!
三、异常的分类
NullPointerException
空引用异常
IndexOutOfBoundException
下标越界异常
Error与编``译环境有关,它是Java运行时的内部错误以及资源耗尽错误。很难修复,不期望用户能修复。
四、获取异常信息
程序发生异常的时候,程序就直接从try执行到catch语句块,不再继续执行`在这里。
public class text3 { public static void main(String[] args) {System.out.println("main开始执行");text3 a=new text3();a.text();System.out.println("main执行结束");} public void text() { int a; try { a=2/0; System.out.println(a); }catch(ArithmeticException e){ System.out.println("程序发生了异常"); } }}
异常捕获之后程序才不会断
public class text3 { public static void main(String[] args) {System.out.println("main开始执行");text3 a=new text3();a.text();System.out.println("main执行结束");} public void text() { int a; //try { a=2/0; System.out.println(a); //}catch(ArithmeticException e){ //System.out.println("程序发生了异常"); //} }}
控制台结果:
异常自己不处理但是得声明一下。
异常声明:指一个方法不处理它所产生的异常,而是调用层次向上传递,谁调用的这个方法谁来处理。
五、手动抛出异常
throw exception; 参数exception表示要抛出的异常对象,该对象是throwable类的子类,而且只能够是一个。
public void text1() throws ArithmeticException{}public static void main(String[] args) {Text t=new Text();try {t.text();} catch (Exception e) {// TODO Auto-generated catch blockSystem.out.println(e.getMessage());}}public void text() throws Exception {//手动抛出异常throw new Exception("这是手动抛出来的");}}
六、try catch finally的嵌套使用
public class Textthrow { public static void main(String[] args) {double a=Math.random(); try { if(a>0.5) { System.out.println(a+"程序不报错"); } else { throw new Exception(); } }catch(Exception e) { System.out.println("这是外层捕获的对象"+e); try { a=1/0; }catch(ArithmeticException e1) { System.out.println("这是内层捕获的对象"+e1); }finally { System.out.println("这是内层的finally块"); } }finally { System.out.println("这是外层的finally块 "); }}}
七、异常链
定义:两个或者多个不同的异常出现在同一个程序中,并且会发生嵌套抛出,我们称之为异常链。
public class ExceptionChainText { public static void main(String[] args) {Calculator c=new Calculator();try {c.chufa(1, 0);}catch(NumberCalculateExcetption e) {e.printStackTrace();System.out.println("错误原因"+e);}}}class Calculator{public int chufa(int i,int j) throws NumberCalculateExcetption {if(j==0) {NumberCalculateExcetption e = newNumberCalculateExcetption ("计算错误");NegativeNumberException e1=newNegativeNumberException("除数不能为0"); e.initCause(e1);//由e1引起的异常 throw e;}return 0;}}class NegativeNumberException extends Exception{public NegativeNumberException(String msg) {super(msg);}}class NumberCalculateExcetption extends Exception{public NumberCalculateExcetption(String msg) {super(msg);}}
关于异常在java中的应用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。