1):?throws ArithmeticException
成都創(chuàng)新互聯(lián)公司專注于新區(qū)企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè),商城網(wǎng)站建設(shè)。新區(qū)網(wǎng)站建設(shè)公司,為新區(qū)等地區(qū)提供建站服務(wù)。全流程定制制作,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務(wù)
2:)new
3:)ArithmeticException
代碼塊里拋異常使用的是throw 關(guān)鍵字, 方法體拋異常使用的是throws 關(guān)鍵字
使用try catch 用于捕獲拋出的異常, 并試圖進(jìn)行處理
完整的參考代碼
public?class?TestThrow?{
static?int?x?=?0;
static?int?y?=?0;
public?static?void?divide()?throws?ArithmeticException?{?//?方法定義拋出異常
if?(x?!=?0)?{
y?=?100?/?x;
}?else?{
throw?new?ArithmeticException("除數(shù)不能為零!");//拋出異常
}
}
public?static?void?main(String[]?args)?{
try?{
divide();
}?catch?(ArithmeticException?e)?{//捕獲方法拋出的異常,并在catch里打印出來
e.printStackTrace();
}
}
}
這種問題寫個(gè)代碼跑一下就可以了,java中整數(shù)除以0會(huì)引發(fā)
java.lang.ArithmeticException: / by zero
ArithmeticException是出現(xiàn)異常的運(yùn)算條件時(shí),拋出此異常,結(jié)果如下圖:
除此之外還要注意,浮點(diǎn)數(shù)除以0將會(huì)的得到 Infinity(無窮大)或NaN結(jié)果,但不會(huì)報(bào)異常。
super("除數(shù)為0異常"); Container container = getContentPane(); container.setLayout(new GridLayout(3, 2)); container.add(new JLabel("輸入被除數(shù)", SwingConstants.RIGHT)); numeratorField = new JTextField(10); container.add(numeratorField); container.add(new JLabel("輸入除數(shù)并回車", SwingConstants.RIGHT)); denominatorField = new JTextField(10); container.add(denominatorField); denominatorField.addActionListener(this); container.add(new JLabel("結(jié)果", SwingConstants.RIGHT)); outputField = new JTextField(); container.add(outputField); setSize(425, 100); setVisible(true);}public void actionPerformed(ActionEvent event) { outputField.setText(""); numerator = Integer.parseInt(numeratorField.getText());// 被除數(shù)try {denominator = Integer.parseInt(denominatorField.getText()); } catch (NumberFormatException ex) {// 捕捉除數(shù)格式異常錯(cuò)誤 System.out.println("I detected Exception" + ex.toString()); return;// 當(dāng)發(fā)現(xiàn)異常的時(shí)候退出方法}try {/** 這個(gè)地方調(diào)用quotient()方法,則必須要捕捉異常*/quotient = quotient(numerator, denominator); } catch (myArithmeticException e) { // TODO Auto-generated catch block System.out.println(e.toString()); outputField.setText(e.toString());return;}outputField.setText(Integer.toString(quotient));}/** 這個(gè)方法拋出異常,那么調(diào)用這個(gè)方法是就要捕捉異常*/public int quotient(int numerator, int deniminator) throws myArithmeticException { if (denominator == 0) throw new myArithmeticException(denominator); return numerator / deniminator;}public static void main(String[] args) { // TODO Auto-generated method stub