Java--异常

异常

异常是程序中的一写错误,但所有的错误都是异常。这些异常有的是因为用户错误引起,有的是程序错误引起的。异常发生的原因有很多,通常包括这三类:
  • . 用户输入了非法数据
  • . 要打开的文件不存在
  • . 网络通信时连接中断,或者JVM内存溢出

Exception类

所有的异常类是从 java.lang.Exception 类继承的子类。

image

捕获异常

使用 try 和 catch 关键字可以捕获异常。

try/catch 代码块放在异常可能发生的地方。try/catch代码块中的代码称为保护代码,使用 try/catch 的语法如下:
try
{
   // 程序代码
}catch(ExceptionName e)
{
   //Catch 块
}
当保护代码块中发生一个异常时,try 后面的 catch 块就会被检查。如果发生的异常包含在 catch 块中,异常会被传递到该 catch 块,这和传递一个参数到方法是一样。

多重捕获

一个try代码块,后面可以跟随多个catch代码块

try{
   // 程序代码
}catch(异常类型1 异常的变量名1){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}catch(异常类型3 异常的变量名3){
  // 程序代码
}

throw throws

throw在方法体中使用,只能抛出⼀个异常对象名。

throws 在方法声明上使用,可以跟多个异常类名,用逗号隔开。

如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明。throws 关键字放在方法签名的尾部。也可以使用 throw 关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。

throws:

import java.io.*;
public class className
{
  public void deposit(double amount) throws RemoteException
  {
    // Method implementation
    throw new RemoteException();
  }
  //Remainder of class definition
}

finally

finally 关键字用来创建在 try 代码块后面执行的代码块。无论是否发生常,finally 代码块中的代码总会被执行。

PTA 例题

判断题:

1.所有异常都必须捕获。 F

不一定,理论上只要是代码就可能出现异常,所以不需要所有异常都要进行处理,可以抛给java虚拟机处理

2.一个try语句可以有多个catch语句与之对应。 T

3.异常也是一个对象。 T

4.用户可以自定义自己的异常类。 T

5.可以使用throw语句来抛出异常。 T

6.可以使用throw语句来抛出异常。 T

7.当一个方法在运行过程中产生一个异常,则这个方法会终止,但是整个程序不一定终止运行。 T

8.程序运行时所产生的系统定义的异常将自动被抛出. T

函数题

1.多种类型异常的捕获

image
image

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
	    while (sc.hasNext()) {
	        String choice = sc.next();
	        try {
	            if (choice.equals("number"))
	                throw new NumberFormatException();
	            else if (choice.equals("illegal")) {
	                throw new IllegalArgumentException();
	            } else if (choice.equals("except")) {
	                throw new Exception();
	            } else
	            break;
	        }
	        catch (NumberFormatException e) {//捕获number异常
				// TODO: handle exception
	        	System.out.println("number format exception");
	        	System.out.println("java.lang.NumberFormatException");
			}
	        catch (IllegalArgumentException e) {//捕获illegal异常
				// TODO: handle exception
	        	System.out.println("illegal argument exception");
	        	System.out.println("java.lang.IllegalArgumentException");
				}
	        catch (Exception e) {//捕获except异常
				// TODO: handle exception
	        	System.out.println("other exception");
	        	System.out.println("java.lang.Exception");
	        }
	    }//end while
	    sc.close();
	}

}

2.求圆面积自定义异常类

image
image

class Circle{
	double radius;
	public Circle(double radius) {
		// TODO Auto-generated constructor stub
		this.radius=radius;
	}
	public double area() throws CircleException{
		if(radius<0) {
			CircleException e=new CircleException(radius);
			throw e;
		}
		return 3.14*radius*radius;
	}
}
class CircleException extends Exception{
	double radius;
	CircleException(double radius){
		this.radius=radius;
	}
	public void print() {
		System.out.println("圆半径为"+radius+"不合理");
	}
}

编程题

成绩录入时的及格与不及格人数统计

image
image


import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner inScanner=new Scanner(System.in);
		int n=inScanner.nextInt();
		int pass=0;
		int fail=0;
		int i=0;
		for (  i= 0;  i< n; ) {
			int num=inScanner.nextInt();
			try{
				if (num>100||num<0) {
				throw new MyException("invalid!");
			}
			else if (num>=60) {
				pass++;
				i++;
			}
			else if (num<60&&num>=0) {
				fail++;
				i++;
			}
				}
			catch (MyException e) {
				// TODO: handle exception
				System.out.println(num+e.toString());
			}
			
			}
		System.out.println(pass);
		System.out.println(fail);
		}
}
class MyException extends Exception{
	public  MyException(String message) {
		super(message);
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "invalid!";
	}
}
posted @ 2022-05-18 18:03  traveller-2333  阅读(34)  评论(0编辑  收藏  举报