【Java中级】(五)异常处理

1.什么是异常

异常定义:导致程序的正常流程被中断的事件,叫做异常。

2.异常处理

try catch finally throws

package exception;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class TestException {

    public static void main(String[] args) {

        File f= new File("d:/LOL.exe");

        try{
            System.out.println("试图打开 d:/LOL.exe");
            new FileInputStream(f);
            System.out.println("成功打开");
        }
        catch(FileNotFoundException e){
            System.out.println("d:/LOL.exe不存在");
            e.printStackTrace();
        }

    }
}

3.异常分类

异常可分为:可查异常,运行时异常和错误三种。
其中,运行时异常和错误又叫非可查异常。
Throwable
这里写图片描述

4.Throwable

Throw是类,Exception和Error都继承自该类。
所以捕捉异常的时候,也可以使用该类进行捕捉。

package exception;

import java.io.File;
import java.io.FileInputStream;

public class TestException {

    public static void main(String[] args) {

        File f = new File("d:/LOL.exe");

        try {
            new FileInputStream(f);
            //使用Throwable进行异常捕捉
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
        }

    }
}

5.自定义异常

5.1 创建异常

创建一个继承Exception的类
提供两个构造方法:
1. 无参的构造方法
2. 有参的构造方法,并调用父类的带参构造方法

class EnemyHeroIsDeadException extends Exception{

    public EnemyHeroIsDeadException(){

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

5.2 抛出异常

  1. 创建自定义异常类实例
  2. 通过Throw/Throws抛出该异常
package charactor;

public class Hero {
    public String name;
    protected float hp;

    public void attackHero(Hero h) throws EnemyHeroIsDeadException{
        if(h.hp == 0){
            throw new EnemyHeroIsDeadException(h.name + " 已经挂了,不需要要施放技能" );
        }
    }

    public String toString(){
        return name;
    }

    class EnemyHeroIsDeadException extends Exception{

        public EnemyHeroIsDeadException(){

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

    public static void main(String[] args) {

        Hero garen =  new Hero();
        garen.name = "盖伦";
        garen.hp = 616;

        Hero teemo =  new Hero();
        teemo.name = "提莫";
        teemo.hp = 0;

        try {
            garen.attackHero(teemo);

        } catch (EnemyHeroIsDeadException e) {
            // TODO Auto-generated catch block
            System.out.println("异常的具体原因:"+e.getMessage());
            e.printStackTrace();
        }

    }
}
原文地址:https://www.cnblogs.com/haxianhe/p/9271007.html