import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExceptionDemo {
public static void main(String[] args) {
method();
method1();
}
// 编译时异常
public static void method1() {
try {
String s = "2020-01-20";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(s);
}catch(ParseException e){
e.printStackTrace();
}
}
// 运行时异常
public static void method(){
try {
int arr[] = {1, 2, 3};
System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
}
}
1.7 异常处置之throws
1.8 自定义异常
public class ScoreException extends Exception{
public ScoreException(){}
public ScoreException(String message){
super(message);
}
}
public class Teacher {
public void checkScore(int score) throws ScoreException{
if(score < 0 || score > 100){
throw new ScoreException("分数应该在1-100之间");
}else{
System.out.println("分数正常");
}
}
}
public class ExceptionDemo {
public static void main(String[] args) {
int score = -1;
Teacher teacher = new Teacher();
try{
teacher.checkScore(score);
}catch (ScoreException e){
e.printStackTrace();
}
}
}
输出结果:
learn.ScoreException: 分数应该在1-100之间
at learn.Teacher.checkScore(Teacher.java:6)
at learn.ExceptionDemo.main(ExceptionDemo.java:11)