day05 异常

异常处理方式:

  1. jvm 处理 运行java程序的抽象计算机 异常名称 异常信息 异常出现的位置
  2. 自己处理
    (1)try catch finally
    (2)throws

所有异常的父类都是Exception

异常的类型

1.运行时异常 extends RuntimeException
2.编译异常 必须自己处理

创建自己的异常

//Person.java
public class Person {
    private int Age;

    public int getAge() {
        return Age;
    }

    public void setAge(int age) throws AgeException{
        if (age>=1 & age<150){
            Age = age;
        }else{
            throw new AgeException("您可能不是人类");  抛出异常
        }
    }
}
//AgeException.java 创建的异常
public class AgeException extends Exception{  //继承Exception
    public AgeException(String message) {
        super(message);	//输出信息
    }
}
//Test.java
public class Test {
    public static void main(String[] args){
        Person person = new Person();
        try{
            person.setAge(500);  //设定年龄
        }catch(AgeException e){
            e.printStackTrace();  //输出异常
        }
    }
}

增强型for循环的使用

for(声明语句:条件表达式){
//代码句子
}

import java.util.HashMap;
import java.util.Map;

public class Testc {
        public static void main(String[] args) {
            Map<Integer, String> pokers = new HashMap<>();
            String[] colors = new String[]{"黑桃", "红桃", "方块", "梅花"};
            String[] numbers = new String[]{"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
            int index = 1;
            for (String color : colors) {  //color自动取数组值,第一次为黑桃,第二次为红桃……
                for (String num : numbers) {	//同理
                    String pai = color + num;
                    pokers.put(index, pai);
                    index++;
                }
            }
            pokers.put(index, "小王");
            index++;
            pokers.put(index, "大王");
            System.out.println(pokers);
        }
}

结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值