首页 技术 正文
技术 2022年11月20日
0 收藏 958 点赞 4,923 浏览 1616 个字

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异常处理——题

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异常处理——题

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,907
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,432
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,247
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,058
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,690
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,728