一、什么是非常
非常就是顺序运转历程中所涌现的不正常征象。
try
:把可能发作非常的代码包起来,当发作非常时,将非常抛出
catch
:捕捉非常并处置惩罚
finally
:不论是不是发作非常,都邑实行
throw
:手动激发一个非常
throws
:定义任何被挪用要领的非常
在线进修视频引荐:java在线视频
二、非常涌现的缘由
用户输入毛病;
代码的毛病;
环境的要素;
非常机制保证了顺序的健壮性!
三、非常的分类
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 block System.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 = new NumberCalculateExcetption ("计算毛病"); NegativeNumberException e1= new NegativeNumberException("除数不能为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入门顺序
以上就是java中的非常概述的细致内容,更多请关注ki4网别的相干文章!