JVM虚拟机默认异常处理机制
Java异常处理:
1.try...catch...
2.throw
1.try...catch...
public class test{
public static void main(String[] args) {
System.out.println("开始");
method();
System.out.println("结束");
}
public static void method(){
int[] arr={1,2,3};
try {
System.out.println(arr[3]); //访问超出索引
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
/*
开始
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at pack2.test.method(test.java:13)
at pack2.test.main(test.java:7)
结束
*/
Exception异常类常用方法
编译时异常和运行时异常
2.throws
throws将异常抛出去,让try_catch_来处理
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class test{
public static void main(String[] args) {
System.out.println("开始");
try {
method();
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
try {
method2();
}
catch (ParseException e){
e.printStackTrace();
}
System.out.println("结束");
}
//编译时异常,不加throws ParseException不能编译
public static void method2() throws ParseException {
String s="2048-08-09";
SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd");
Date d=sdf.parse(s);
System.out.println(d);
}
//运行时异常,不加throws ArrayIndexOutOfBoundsException可以编译
public static void method() throws ArrayIndexOutOfBoundsException{
int[] arr={1,2,3};
System.out.println(arr[3]);
}
}
/*
开始
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at pack2.test.method(test.java:36)
at pack2.test.main(test.java:13)
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.Scanner;
public class test{
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();
}
}
}