手机
当前位置:查字典教程网 >编程开发 >Java >一道关于java异常处理的题目
一道关于java异常处理的题目
摘要:1、建立exception包,编写TestException.java程序,主方法中有以下代码,确定其中可能出现的异常,进行捕获处理。pub...

1、建立exception包,编写TestException.java程序,主方法中有以下代码,确定其中可能出现的异常,进行捕获处理。

public class YiChang { public static void main(String[] args){ for(int i=0;i<4;i++){ int k; switch(i){ case 0: int zero=0; try{ k=911/zero; }catch(ArithmeticException e){ System.out.println("出现算数异常!"); } break; case 1: try{ int b[]=null; k = b[0]; }catch(NullPointerException e){ System.out.println("出现空指针异常!"); } break; case 2: int c[]=new int[2]; try{ k=c[9]; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("出现数组序号溢出!"); } break; case 3: try{ char ch="abc".charAt(99); }catch(StringIndexOutOfBoundsException e){ System.out.println("出现数据类型转换异常!"); } break; } } } }

一道关于java异常处理的题目1

2、建立exception包,建立Bank类,类中有变量double balance表示存款,Bank类的构造方法能增加存款,Bank类中有取款的发方法withDrawal(double dAmount),当取款的数额大于存款时,抛出InsufficientFundsException,取款数额为负数,抛出NagativeFundsException,如new Bank(100),表示存入银行100元,当用方法withdrawal(150),withdrawal(-15)时会抛出自定义异常。

public class InsufficientFundsException extends Exception { public String getMessage(){ return "您的余额不足!"; } } public class NagativeFundsException extends Exception{ public String getMessage(){ return "取款金额不能为负数!"; } } public class Bank { private static double balance; Bank(){ }; Bank(double balance){ this.balance=balance; } public static void withDrawal(double dAmount) throws InsufficientFundsException,NagativeFundsException{ if(dAmount>balance){ throw new InsufficientFundsException(); } if(dAmount<0){ throw new NagativeFundsException(); } } public static void main(String[] args){ Bank b=new Bank(100); System.out.println("我有"+balance+"元存款!"); try{ withDrawal(150); }catch(InsufficientFundsException | NagativeFundsException e){ e.printStackTrace(); } try{ withDrawal(-15); }catch(NagativeFundsException |InsufficientFundsException e){ e.printStackTrace(); } } }

一道关于java异常处理的题目2

一道关于一道关于java异常处理的题目就给大家介绍这么多,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家对查字典教程网的支持!

【一道关于java异常处理的题目】相关文章:

浅析java中Integer传参方式的问题

java实现斐波那契数列的3种方法

封装了一个Java数据库访问管理类

Java在Linux下 不能处理图形的解决办法 分享

关于java 图形验证码的解决方法

关于JAVA 数组的使用介绍

Java序列化机制与原理的深入分析

java多线程中的异常处理机制简析

基于java中反射的总结分析

用Java实现希尔排序的示例

精品推荐
分类导航