10){//抛出try {">
赞
踩
以下为这五个关键词的使用方法:
package exception; public class Demo02 { public static void main(String[] args) { //假设要捕获多个异常:从小到大去写 try { new Demo02().a(); }catch (Error e){//catch(想要捕获的异常类型) 捕获异常 System.out.println("ERROR"); }catch (Exception e){ System.out.println("EXCEPTION"); }catch (Throwable e){ System.out.println("THROWABLE"); }finally { System.out.println("finally"); } } public void a() { b(); } public void b() { a(); } }
package exception; import org.w3c.dom.ls.LSOutput; public class Demo03 { public static void main(String[] args) { int a=1; int b=0; try { System.out.println(a/b); } catch (Exception e) { throw new RuntimeException(e); } finally { } } }
package exception; public class Demo01 { public static void main(String[] args) { new Demo01().test(1,0); } //假设这方法中,处理不了这个异常,方法上抛出异常用throws public void test(int a,int b) throws ArithmeticException { if(b==0){ throw new ArithmeticException(); } System.out.println(a/b); } } /* int a=1; int b=0; try{//try监控区域 if(b==0){//throw throws用于方法 throw new ArithmeticException();//主动抛出异常 } System.out.println(a/b); }catch (ArithmeticException e){ System.out.println("程序出现异常,变量b不能为0"); } finally {//善后工作 System.out.println("finally"); } //finally 可以不要finally */
步骤:
package exception; //自定义异常 public class MyException extends Exception{ //传递数字>10 private int detail; public MyException(int a){ this.detail=a; } //toString:异常的打印信息 @Override public String toString() { return "Demo04{" + "detail=" + detail + '}'; } }
我们来测试下
package exception; public class Test { static void test(int a) throws MyException { System.out.println("传递的参数为:"+a); if(a>10){ throw new MyException(a);//抛出 } System.out.println("OK"); } public static void main(String[] args) { try { test(1); } catch (MyException e) { System.out.println("MyException=>"+e); } } }
总结:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。