Error和Exception
public class Demo01 {
public static void main(String[] args) {
new Demo01().a();//匿名内部类 a调b ,b调a无线循环下去,就会出错(Error)严重错误
}
public void a(){//递归调用
b();//在a里面调用b
}
public void b(){
a();
}
}
/*
Exception in thread "main" java.lang.StackOverflowError
*/
-----------------------------------------------------------------
public class Demo01 {
public static void main(String[] args) {
System.out.println(11 / 0);//0不能当做被除数
}
}
/*
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.exception.Demo01.main(Demo01.java:5)
*/
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{//try监控区域
System.out.println(a/b);
}catch(ArithmeticException e){//捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally{//处理善后工作
System.out.println("finally");
}
}
}
/*
程序出现异常,变量b不能为0
finally
*/
-----------------------------------------------------------------
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要捕获多个异常:从小到大!
try{//try监控区域
// new Test().a();//对象.方法
System.out.println(a/b);
}catch(Error e){//catch(想要捕获的异常类型)捕获异常
System.out.println("程序出现异常,变量b不能为0");
}catch(Exception e){
System.out.println("Exception");
}catch(Throwable c){
System.out.println("Throwable");
}finally{//处理善后工作
System.out.println("finally");
}
//finally 可以不要finally,假设IO,资源,关闭!
}
public void a(){
b();
}
public void b(){
a();
}
}
/*
Exception
finally
*/
-----------------------------------------------------------------
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//选中这行代码,自动驱动代码块。快捷键 ctrl+alt+t
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();//打印错误的栈信息
} finally {
}
//System.out.println(a/b);
}
}
/*
java.lang.ArithmeticException: / by zero
at com.exception.Test2.main(Test2.java:10)
*/
-----------------------------------------------------------------
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0);//匿名内部类
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设这方法中,处理不了这个异常,方法上抛出异常
public void test (int a,int b)throws ArithmeticException{
if(b==0){// throw throws
throw new ArithmeticException();//主动的抛出异常,一般在方法中使用
}
}
}
/*
java.lang.ArithmeticException
at com.exception.Test.test(Test.java:18)
at com.exception.Test.main(Test.java:7)
*/
自定义异常及小结
LeetCode:面试刷题