Java简单应用--异常类(五)

一、判断异常类型

(一)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Input{
public static String input(){
String result=null;
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
result = in.readLine();}
catch (IOException e)
{
System.out.println("IO exception!!!");
}
return (result);
}
public static void main(String[] args){
int i;
char a[] = new char[5];
String buffer;
try{
System.out.print("请输入字符:");
buffer=input();
for(i=0;i<buffer.length();i++)
a[i]= buffer.charAt(i);
System.out.println("输入的字符序列为:"+buffer);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("出现异常:数组越界!!!");
}
}
}

运行结果:
在这里插入图片描述
(二)

public class Add {
    public static void main(String[] args) {
      if (args.length == 0) {
        try {
          throw new NoprondException();
        }
        catch (NoprondException e) {
          e.printStackTrace();
        }
      }
      else if (args.length == 1) {
        try {
          throw new OnlyOneException();
        }
        catch (OnlyOneException e) {
          e.printStackTrace();
        }
      }
      else {
		double a, b;
		a = Double.parseDouble(args[0]);
		b = Double.parseDouble(args[1]);
        System.out.println(a + b);
      }
    }
}
class NoprondException extends Exception {
    public void printStackTrace() {
      System.out.println("NoprandException");
      super.printStackTrace();
    }
}
class OnlyOneException extends Exception {
    public void printStackTrace() {
      System.out.println("OnlyOneException");
      super.printStackTrace();
    }
}

运行结果:
在这里插入图片描述
(三)

import java.io.*;
import java.io.BufferedReader;
public class MyException{
public static void main(String[] args)
{
System.out .println(" 请输入一个整数字符串 " );
try
{
BufferedReader in=new BufferedReader(new InputStreamReader (System.in ));
//设置输入端为键盘
int i=Integer.parseInt (in.readLine());//将整数字符串转化为整型
System.out .println("您输入的整数是:"+i);//从键盘上输入数据
}
catch (IOException e)//如果捕获到是输入输出异常
{
System.out .println("输入输出错误 " );//则输出输入输出错误
}
catch (NumberFormatException e)//该catch捕获数字格式化异常,则不是整数字符串
{
System.out .println(" 您输入的字符串不是一个整数字符串 " );
}
}
}

运行结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值