0
点赞
收藏
分享

微信扫一扫

EduCoder Java程序设计---Java面向对象(六) - Java中的异常

王小沫 2022-04-18 阅读 28

第1关 Java 中的异常处理机制

 

 第2关 捕获异常

package step2;

import java.util.Scanner;

public class Task {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num1 = sc.nextInt();
		int num2 = sc.nextInt();
		/********* Begin *********/
		
		try{
	
			System.out.println(num1/num2);
		}catch(ArithmeticException e){
			System.out.println("除数不能为0");
		}
		
		
		/********* End *********/
	}

}

第3关 抛出异常

package step3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Task {
	/********* Begin *********/
	//请在合适的部位添加代码
	public static void main(String[] args) throws FileNotFoundException      {	
		test();
	}
	public static void test()throws FileNotFoundException        {
		File file = new File("abc");
		if(!file.exists()){		//判断文件是否存在
			//文件不存在,则 抛出 文件不存在异常
			throw new FileNotFoundException("该文件不存在");
		}else{
			FileInputStream fs = new FileInputStream(file);
		}
	}
	/********* End *********/
}

第4关 自定义异常

package step4;
import java.util.Scanner;
public class Task {
	/********* Begin *********/
	public static void main(String[] args) throws MyException{
		Scanner sc = new Scanner(System.in);
		String username = sc.next();
		//判断用户名
		if(username.length()<3){
			throw new MyException("用户名小于三位Exception");
		}else{
			System.out.println("用户名格式正确");
		}
	}
}

class MyException extends Exception{
	private static final long serialVersionUID = 1L;

	public MyException(){

	}
	public MyException(String msg){
		super(msg);
	}
	
}

/********* End *********/
举报

相关推荐

0 条评论