Java异常处理

设有一个整数数组a[10],为其赋值为0到9的值,从键盘输入整数i的值,求a[i]的倒数,注意处理各种异常。发生异常后,根据不同的异常,输出警告。

提示:

    需要考虑NumberFormatException、ArrayIndexOutOfBoundsException、ArithmeticException、IOException等多种异常。

import javax.swing.JOptionPane;

public class Main {

 public static void main(String[] args) {
  
  final int aryLength = 10;

  int[] ary = new int[aryLength];
  fillAry(ary);
  
  calcDaoshu(getInputFromKeyBoard());
  
 }

 private static void calcDaoshu(int value) {
  try{
   double input  = 1/value;
   System.out.println(input);
  }catch(ArithmeticException arithmeticExp){
   JOptionPane.showMessageDialog(null, "Can't be divided by ZERO!");
  }
 }

 private static void fillAry(int[] ary) {

  for(int i = 0; i <= ary.length; i++){
   try{
    ary[i] = i;
   }catch(ArrayIndexOutOfBoundsException exp){
    JOptionPane.showMessageDialog(null, " Error! Array index out of bounds.");
    break;
   }
  }
  
 }

 private static int getInputFromKeyBoard() {
  int value = 0;
  
  boolean isDigit = false;
  
  while(!isDigit){
   String input = JOptionPane.showInputDialog("Please input a digit number");
   
   try {
    value = Integer.parseInt(input);
    isDigit = true;
   } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(null, "Invalid digit value, please input again!");
   }
   
  }
  return value;
 }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java异常处理是一种机制,它允许程序在执行期间处理可能出现的错误。当程序出现错误时,它会抛出一个异常,并且程序可以选择捕捉这个异常并采取适当的措施来解决问题。在Java中,异常是一个对象,它表示发生了某种错误或异常情况。Java中的异常分为两种:Checked Exceptions和Unchecked Exceptions。 Checked Exceptions是在编译时强制要处理的异常,例如IOException和SQLException。Unchecked Exceptions则不需要在编译时强制要处理,例如NullPointerException和ArrayIndexOutOfBoundsException。 Java异常处理使用try-catch语句块。try块包含可能会抛出异常的代码,而catch块用于捕获并处理异常。如果try块中的代码抛出异常,程序将跳转到catch块,执行相应的处理代码。如果没有catch块可以处理该异常,则该异常将传递给调用该方法的上层方法,直到找到一个合适的catch块或者程序终止。 除了try-catch语句块,Java还提供了finally块,它包含一些代码,无论try块是否抛出异常,都会被执行。finally块通常用于释放资源或清理代码。 下面是一个简单的Java异常处理的示例: ```java try { // 可能会抛出异常的代码 } catch (ExceptionType e) { // 处理异常的代码 } finally { // 清理代码或释放资源的代码 } ``` 总体来说,Java异常处理是一种重要的机制,它可以帮助开发人员更好地管理和处理程序中可能出现的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值