java try catch块的简单解析



try catch作用是抓取异常,

快速添加方式:选中部分需要异常抓取的块,右击鼠标,鼠标放在source with 即可看到 try catch 块

package a13;

import java.util.Scanner;

public class Ouotient {

 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  
       int a,b;
       a = input.nextInt();
       b = input.nextInt();
   
        try {
   if(b==0)
       throw new ArithmeticException("Divisor cannot be zero");//如果是异常,会扔出异常信息,即此处遇到异常,就会执行catch部分,catch部分执行完毕后,

//异常下面的语句正常执行
      System.out.println(a/b);
     }
        
      catch (ArithmeticException ex) {//可以有多个catch针对不同异常,

//常见的有IOException是Io异常无效的输入,读文件时超出文件尾等,还有,RuntimeException越界异常,

//其包括ArithmeticException数学异常,一个整数除以0,注意浮点数的算术运算不抛出异常

//NullPointerException企图通过一个NULL引用变量访问一个对象,IndexOutBoundsException数组下标超出范围,

//IllegalArgumentExection无效参数
         System.out.println("Exception: an integer cannot be divided by zero");
   
   }
 
       System.out.println("Execution continues......");
 }

}


也可以对文件读取,改写等抓取异常

package a13;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileNotFoundExceptionDemo {

 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.println("Enter a file name :");
  String filename = input.nextLine();
  try {
   Scanner input1 = new Scanner(new File(filename));
   System.out.println("file "+filename+" exit ");
  }
  catch (FileNotFoundException ex) {
   System.out.println("Exception "+filename +" not found");
  }
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

洋葱ycy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值