异常处理方式:
- jvm 处理 运行java程序的抽象计算机 异常名称 异常信息 异常出现的位置
- 自己处理
(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);
}
}
结果