GDPU Java 天码行空9 异常及处理

(一)实验目的

1、掌握JAVA中异常类型及其特点;
2、重点掌握异常的处理方法;
3、能创建自定义异常处理方法;
4、掌握文件操作方法。

(二)实验内容和步骤

1、try catch finally

如果catch里面有return语句,请问finally的代码还会执行吗?

答:会

如果会,请问是在return前还是return后

答:后

请使用debug方法查看程序中的变量a的取值是多少

答:40(finally 语句对 a 进行了重新赋值,但并不影响已经准备 return的值 30)

如果将最后一名return a;语句移到finally中,那么又会是什么情况。

答:返回 40

💖FinallyDemo2.java

public class FinallyDemo2 {
	public static void main(String[] args) {
		System.out.println(getInt());
	}
	public static int getInt() {
		int a = 10;
		try {
			System.out.println(a / 0);
			a = 20;
		} catch (ArithmeticException e) {
			a = 30;
			return a;
			
		} finally {
			a = 40;
//return a; 
		}
		return a;
	}
}

2、父子类异常

当出现继承关系时,异常处理中要注意下面三中情况:

  • 子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。
  • 如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常
  • 如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws。
    请在下面代码的基础上,通过增加、修改代码对上面三种情况进行测试。
    💖 ExceptionDemo.java
public class ExceptionDemo {
}

class Fu {
	public void show() throws Exception {
	}

	public void method() {
	}
}

class Zi extends Fu {
	@Override
//	public void show() throws Exception{
	public void show() throws ArithmeticException {

	}

	//测试throws和try方法
	@Override
	public void method() {
		// String s = "2014-11-20";
		// SimpleDateFormat sdf = new SimpleDateFormat();
		// Date d = sdf.parse(s);
		// System.out.println(d);
	}
}

在这里插入图片描述
在这里插入图片描述


在这里插入图片描述


在这里插入图片描述

3、验证一些例子程序

在此基础上,编写一个程序,创建自己的异常,对程序接受的数据输入进行异常的捕捉和处理。

异常处理

因为System.in.read()方法会抛出 IOException 异常,而程序中没有 try-catch-finally 语句进行捕获处理,故必须在main()方法的头部加上throws IOException,明确表示对该异常,程序不想处理,交由调用者处理。当然main()方法的调用者是JVM,一旦有异常,程序即使运行结束

import java.io.*;
public class Excep
{
	public static void main(String args[])  //throws IOException
	{
		int c;
		//try{
		while((c=System.in.read())!=-1)
			System.out.println(c);
		//}
		//catch(IOException e)
		//{ }
	}
}

系统已定义的标准异常

import java.io.*;

public class UseException
{
	public static void main(String args[])
	{
		System.out.println("Please Input an Interger:");
		try
		{ // 此处可能会抛出I/O异常
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			int a = Integer.parseInt(in.readLine()); // 此处可能会抛出数据格式异常
			System.out.println("the Integer you input is:" + a);
//			throw new IOException(); //手动抛一个 IOException
		} catch (IOException e) // 捕获I/O异常并处理
		{
			System.out.println("I/O error");
		} catch (NumberFormatException ne)
		{
			System.out.println("what you input is not an Integer!");
		}
	}
}

在这里插入图片描述


在这里插入图片描述

自定义异常的简单例子

注意观察自定义异常类里的语句和catch内的语句,以及finally内的语句,运行的先后顺序,先用未注释的,然后将注释符号去掉再观察。

class myexcep extends Exception
{
	// myexcep()
	// {System.out.println("Excep occured");}
}

public class UseExcp
{
	static void f1() throws myexcep
	{
		System.out.println("方法调用抛出异常");
		throw new myexcep();
	}

	public static void main(String args[])
	{
		try
		{
			f1();
		} catch (myexcep e1)
		{
			System.out.println("catch 捕捉异常");
			System.out.println("Exception 1");
		} finally // 可要可不要的finally部分
		{
			System.out.println("finally 收拾烂摊子");
			System.out.println("this part can remain or not!");
		}
	}
}

在这里插入图片描述

用户自定义异常

class ArgumentOutOfBoundsException extends Exception //自定义一种异常
{
  ArgumentOutOfBoundsException()
  {
System.out.println("输入错误!欲判断的数不能为负数!");
   }
}
public class useexcp
{
  public static boolean prime(int m) throws ArgumentOutOfBoundsException
  {
if(m<0)
{   ArgumentOutOfBoundsException ae=new ArgumentOutOfBoundsException();
    throw ae;
}
else
{  boolean isPrime=true;
   for(int i=2;i<m;i++)
     if(m%i==0)  {  isPrime=false;   break;   }
   return isPrime;
}
}
public static void main(String args[])
{
 if(args.length!=1)
{
 System.out.println("输入格式错误!请按照此格式输入:java Usedefine Exception m");
 System.exit(0);
}
int m=Integer.parseInt(args[0]);   //读入这个整数
try
{   boolean result=prime(m);   //调用方法判断是否为素数
System.out.println("对您输入的整数"+m+"是否为素数的判断结果为:"+result);
}
catch(ArgumentOutOfBoundsException e)
{   System.out.println("异常名称:"+e.toString());  }
}
}

在这里插入图片描述

4、实现程序

(1)不限定输入数据的个数,在数组越界时产生数组越界异常ArrayIndexOutOfBoundsException.
(2)在输入非数字字符时,产生NumberFormatException。
💖 Main.java

import java.util.Scanner;

public class Main
{
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		int[] numbers = new int[3]; // 假设数组大小为3
		int index = 0;

		while (true)
		{
			System.out.print("请输入一个数字(输入'q'退出): ");
			String input = scanner.nextLine();

			if ("q".equals(input))
			{
				break; // 退出循环
			}

			try
			{
				int number = Integer.parseInt(input);
				numbers[index] = number;
				index++;
			} catch (NumberFormatException e)
			{
				e.printStackTrace();
				System.out.println(e.getMessage());
			} catch (ArrayIndexOutOfBoundsException e)
			{
				e.printStackTrace();
				System.out.println("数组越界,无法添加更多数字。");
			}
		}

		// 打印输入的数字
		System.out.println("你输入的数字有:");
		for (int i = 0; i < index; i++)
		{
			System.out.println(numbers[i]);
		}
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值