java自定义异常抛出

Python020

java自定义异常抛出,第1张

分类: 电脑/网络 >>程序设计 >>其他编程语言

问题描述:

import java.awt.*

import java.awt.event.*

import javax.swing.*

自定义异常

class NumException extends Exception{

public String toString(){

return "输入的值太小"

}

public String shuru(){

return "请输入数字"

}

}

class jisuanqi extends JFrame implements ActionListener,ItemListener{

JRadioButton rz

JRadioButton rm

ButtonGroup bg

JTextField txt

JButton btnj

String msg

jisuanqi(){

super("计算器")

rz=new JRadioButton("周长")

rm=new JRadioButton("面积")

bg=new ButtonGroup()

txt=new JTextField()

btnj=new JButton("计算")

msg=""

this.getContentPane().setLayout(new GridLayout(2,2))

bg.add(rz)

bg.add(rm)

this.getContentPane().add(rz)

this.getContentPane().add(rm)

this.getContentPane().add(txt)

this.getContentPane().add(btnj)

this.setSize(200,200)

rz.addItemListener(this)

rm.addItemListener(this)

btnj.addActionListener(this)

}

实现接口

public void actionPerformed(ActionEvent e) throws NumException{声明异常

if (Double.parseDouble(txt.getText())<=0){

throw new NumException()抛出异常

}

if (msg.equals("周长")){

txt.setText(""+(3.14*2*Double.parseDouble(txt.getText())))

}

if (msg.equals("面积")){

txt.setText(""+3.14*(Double.parseDouble(txt.getText())*Double.parseDouble(txt.getText())))

}

}

实现接口

public void itemStateChanged(ItemEvent e){

if (e.getSource()==rz){

msg="周长"

}

if (e.getSource()==rm){

msg="面积"

}

}

public static void main(String args[]){

try{

jisuanqi js=new jisuanqi()

js.setVisible(true)

}

catch(NumException ex){

System.out.println(ex)

}

}

}

编译时出现:

C:\Documents and Settings\Administrator\桌面\新建文件夹\jisaunqi.java:45: jisuanqi 中的 actionPerformed(java.awt.event.ActionEvent) 无法实现 java.awt.event.ActionListener 中的 actionPerformed(java.awt.event.ActionEvent);被覆盖的方法不抛出 NumException

解析:

这段代码有问题:

实现接口

public void actionPerformed(ActionEvent e) throws NumException{声明异常

public void actionPerformed(ActionEvent e)不应该抛出异常, ActionListener接口函数没有异常抛出

一种可能的解决方法是把判断移到另外一个函数中,然后抛出异常,在actionPerformed中捕获或者在外面捕获

public class Bank {

private Integer moneyTotal

//存款

public Integer saveMoney(Integer moneyConut) throws Exception {

if(moneyConut<0){

throw new Exception("存款异常")

}

return moneyConut+moneyTotal

}

//取款

public Integer getMoneyCoun(Integer moneyCount) throws Exception {

if(moneyTotal-moneyCount<0){

throw new Exception("取款异常")

}

return moneyTotal-moneyCount

}

}