解决异常的方法:
package 异常;
public class ExceptionDemo1 {
public static void main(String[] args) {
System.out.println("开始");
method();
System.out.println("结束");
}
public static void method(){
try {
int[] arr={1,2,3};
System.out.println(arr[3]);
}catch(ArrayIndexOutOfBoundsException e){
// System.out.println("你访问的数组索引不存在");
e.printStackTrace();
}
}
}
package 异常;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExceptionDemo2 {
public static void main(String[] args) {
System.out.println("开始");
try {
method();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("结束");
}
public static void method() throws ParseException {//格式
String s="2030-11-10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
Date d=sdf.parse(s);//parse这里的异常
}
}
自定义异常:
package 异常.自定义异常;
public class ScoreException extends Exception {
public ScoreException(){}
public ScoreException(String message) {
super(message);
}
}
package 异常.自定义异常;
public class Teacher {
public void checkScore(int score) throws ScoreException {
if (score<0||score>100) {
throw new ScoreException("你给的分数有误");
}else{
System.out.println("分数正常");
}
}
}
package 异常.自定义异常;
import java.util.Scanner;
public class TeacherText {
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) {
e.printStackTrace();
}
}
}



