异常
所有的异常都是继承自Throwable类,异常又分为Error和Exception。
Error:指Java运行时系统的内部错误和资源耗尽错误。
Exception:分为RuntimeException和IOException。
自定义异常
import java.util.Scanner;
class exception extends Exception{
public exception(){}
public exception(String s){
super(s);
}
}
public class TestDemo5{
public static void fun1() throws exception {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if(a <= 0){
throw new exception("异常");
}
}
public static void main(String[] args) throws exception {
fun1();
}
}
捕获异常
try…catch块:
public static void fun()throws ArithmeticException{
try {
int a = 10;
int b = 0;
int c = a/b;
System.out.println(c);
}catch (ArithmeticException e){
System.out.println("运算异常");
e.printStackTrace();//打印异常信息栈
}
}
public static void fun3(){
try {
String str = "abcdef";
System.out.println(str.charAt(6));
}catch (StringIndexOutOfBoundsException e){
System.out.println("字符串越界异常");
e.printStackTrace();//打印异常信息栈
}
}
try…catch finally:
public static void Calculate () //这里已经处理了异常,不需要再声明异常了
//如果加了声明,当前函数就不处理了,调用该函数的一方进行处理。
{
Scanner scan = new Scanner ( System. in );
try {
int num1 = scan .nextInt () ;
int num2 = scan .nextInt () ;
int result = num1/num2 ;
System . out. println( "result:" + result) ;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException 异常");
e.printStackTrace();
} catch (InputMismatchException e) {//输入有误的时候
System.out.println("InputMismatchException 异常");
e.printStackTrace();
} finally {
scan .close ();//释放资源
}
}
警告:当finally子句包含return语句时,将会出现一种意想不到的结果,假设利用return语句从try语句中退出,在方法返回前,finally子句的内容将被执行。如果finally子句中也有一个return语句,这个返回值将会覆盖try语句中的返回值。
public int fun2(){//该方法返回的值为3,因为finally中的方法覆盖了try...catch块中的return
try{
return 1;
}catch (Exception e){
return 2;
}finally {
return 3;
}
}