Educoder-Java程序开发基础-异常处理之一

2021/7/20 11:05:44

本文主要是介绍Educoder-Java程序开发基础-异常处理之一,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

捕获异常

try{
    A
    B
}catch(Exception e){
    异常处理
}
	C

try:尝试,catch:捕获; 尝试执行代码A代码B如果这两段代码有一个出现了异常,就会执行catch中的语句,如果代码A、B都不存在异常就不会执行catch代码,最后继续执行代码C

​ 本关任务:捕获程序的异常,输出异常处理的结果

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(Exception e){
            System.out.print("除数不能为0");
        }
        /********* End *********/
    }
}

抛出异常

throw 关键字

throw关键字的作用是:主动抛出异常

throw是语句抛出一个异常,一般是在代码块的内部,当程序出现某种逻辑错误时由程序员主动抛出某种特定类型的异常

注意:使用throw关键字主动抛出检测性异常的时候,在方法名上必须使用throws表明调用这个方法可能存在要抛出的异常。

//方法一
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 *********/
}
//方法二:
public class Task {
	/********* Begin *********/
	//请在合适的部位添加代码
	public static void main(String[] args)       {	
		try{
			test();
		}catch(FileNotFoundException e){
			e.printStackTrace();
			System.out.println("该文件不存在");
		}
	}
	public static void test() throws FileNotFoundException          {
		File file = new File("abc");
		if(!file.exists()){		//判断文件是否存在
			//文件不存在,则 抛出 文件不存在异常
			throw new FileNotFoundException("该文件不存在");
		}else{
			FileInputStream fs = new FileInputStream(file);
		}
	}
	/********* End *********/
}

自定义异常

前面谈到的都是系统自带的异常,但是如果我们是在开发一个复杂项目,就经常会遇到系统自带的异常不能满足我们的需求的情况,所以这个时候就需要我们自己来定义异常了

使用自定义异常

很简单,我们只需要继承Exception,再将信息传递给父类就可以了:

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();
        }else
            System.out.print("用户名格式正确");

    }
}

class MyException extends Exception{        //自定义异常继承Exception
    private static final long serialVersionUID=1L;
    public MyException(){
        super("用户名小于三位Exception");      //抛出MyException时显示...
    }
    public MyException(String msg){
        super(msg);
    }
}

/********* End *********/

自定义异常及处理

package step5;

import java.io.*;
//用户定义的异常类UnSafePasswordException,由Exception类派生,补充完善代码

//begin
class UnSafePasswordException extends Exception {

    private static final long serialVersionUID = 1L;

    public UnSafePasswordException() {
        //调用父类Exception的构造方法,并设置异常信息为"密码过于简单,安全密码的长度应大于6,且必须包含数字、大写字符和小写字母!"
        super("密码过于简单,安全密码的长度应大于6,且必须包含数字、大写字符和小写字母!");
    }

    public UnSafePasswordException(String msg) {
        super(msg);
        //调用父类Exception的构造方法
    }
}
//end
public class ExceptionTest06Step {

    // 密码检查方法checkPassword需要抛出异常UnSafePasswordException,补充完善代码
    //begin
    static void checkPassword(String strPassword)  throws UnSafePasswordException{		//throws放在方法名
        if (strPassword.length() < 6)
            throw new UnSafePasswordException("密码长度太短!");//补充抛出异常代码
        boolean bNumber = false;
        boolean bUpper = false;
        boolean bLower = false;
        for (int i = 0; i < strPassword.length(); i++) {
            if (bUpper && bLower && bNumber)
                break;
            if (strPassword.charAt(i) >= 'a' && strPassword.charAt(i) <= 'z')
                bLower = true;
            if (strPassword.charAt(i) >= 'A' && strPassword.charAt(i) <= 'Z')
                bUpper = true;
            if (strPassword.charAt(i) >= '0' && strPassword.charAt(i) <= '9')
                bNumber = true;
        }
        if (bUpper && bLower && bNumber) {
            System.out.println("密码是安全的!");
            return;
        } else {
            throw new UnSafePasswordException("密码太简单!密码必须同时有大小写字母和数字!");//补充抛出异常代码
        }
    }
    //end
    public static void main(String args[]) {
        //异常捕获和处理,请补充完善代码
        try{
            //System.out.println("请输入密码: ");
            BufferedReader stdin = new BufferedReader(new InputStreamReader(
                    System.in));
            checkPassword(stdin.readLine());
        } catch (UnSafePasswordException e   ) {	//抛出自定义异常
            System.out.println(e.getMessage());
        } catch (Exception e) {		//抛出系统异常
            //System.out.println(e.getMessage());
            System.out.println("发生一般的异常!");
        }
    }
}



这篇关于Educoder-Java程序开发基础-异常处理之一的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程