这个就是类似于提示你的代码有问题,我觉用处并不是太大。
抛出异常
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Yichang2 {
public static void main(String[] args) {
method();
method2();
try {
method3();//throw并没有解决问题
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void method3() throws ParseException {
String s = "2048-08-09";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(s);
System.out.println(d);
}
//编译时异常
public static void method2() {
try {
String s = "2048-08-09";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(s);
System.out.println(d);
}catch(ParseException e){
e.printStackTrace();
}
}
//运行时时异常
public static void method() {
try {
int[] a = {1,2,3};
System.out.println(a[3]);
}catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();//这个方法在输出的信息是最全的一般都用它
}
}
}
输出:
java.lang.ArrayIndexOutOfBoundsException: 3
at com.yichang.test.Yichang2.method(Yichang2.java:39)
at com.yichang.test.Yichang2.main(Yichang2.java:9)
Sun Aug 09 00:00:00 CST 2048
Sun Aug 09 00:00:00 CST 2048
自定义异常
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("你给的分数有误");
}else{
System.out.println("分数正常");
}
}
}
import java.util.*;
public class Teachertest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入分数:");
int score = sc.nextInt();
Teacher t = new Teacher();
try {
t.checkScore(score);
} catch (ScoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出:
请输入分数:
120
com.yichang.test.ScoreException: 你给的分数有误
at com.yichang.test.Teacher.checkScore(Teacher.java:6)
at com.yichang.test.Teachertest.main(Teachertest.java:10)