当前位置: 移动技术网 > IT编程>开发语言>Java > 一道关于java异常处理的题目

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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;
}
}
}
}

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异常处理的题目就给大家介绍这么多,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网