①
源代码:
package cn.ecut.Exception;
/**
* Java三种类型的异常
* 1、检查性异常(IOException):最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的
* 例如要打开一个不存在的文件时,一个异常就发生了,这些异常在编译时不能简单地忽略
* 2、运行时异常(RuntimeException):运行时异常是可能被程序员避免的异常,与检查性异常相反,运行时异常可以在编译时被忽略
* 3、错误(Error):错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了
* 它们在编译时被忽略
*
* 关键字:try catch finally throw throws
*
* Error和Exception的区别:Error通常是灾难性的致命的错误,是程序无法控制和处理的,当出现这些异常时,Java虚拟机(JVM)
* 一般会选择终止线程;Exception通常情况下是可以被程序处理的,并且在程序中应该尽可能的去处理这些异常
*/
public class Demo1 {
public static void main(String[] args) {
int a=1;
int b=0;
try{ //try监控区域
System.out.println(a/b);
}catch(ArithmeticException e){ //catch 捕获异常
System.out.println("分母不能为0!");
}finally{ //finally 处理善后工作
System.out.println("finally");
}
}
}
运行结果:
分母不能为0!
finally
②
源代码:
package cn.ecut.Exception;
public class Demo2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要捕获多个异常:从小到大!
try { //try监控区域
System.out.println(a / b);
} catch (Error e) { //catch 捕获异常
System.out.println("Error!");
} catch (Exception e) {
System.out.println("Exception!");
} catch (Throwable t) {
System.out.println("Throwable!");
} finally { //finally 处理善后工作
System.out.println("finally");
}
}
}
运行结果:
Exception!
finally
③
源代码:
package cn.ecut.Exception;
public class Demo3 {
public static void main(String[] args) {
int a=1;
int b=0;
try{ //try监控区域
System.out.println(a/b);
}catch(Exception e){ //catch 捕获异常
e.printStackTrace(); //打印错误信息
}finally{ //finally 处理善后工作
System.out.println("finally");
}
}
}
运行结果:
java.lang.ArithmeticException: / by zero
at cn.ecut.Exception.Demo3.main(Demo3.java:10)
finally
④
源代码:
package cn.ecut.Exception;
public class Demo4 {
public static void main(String[] args) {
try{
new Demo4().test(1,0);
}catch(ArithmeticException e){
System.out.println("分母不能为0!");
e.printStackTrace();
}
}
//假设在这方法中,处理不了这个异常(没有try...catch),方法上抛出异常(throws),谁调用这个方法谁就要处理这个异常
//调用者可以选择捕获异常(try...catch)或者继续向上抛出异常(throw)
public void test(int a,int b)throws ArithmeticException{
if(b==0){
throw new ArithmeticException(); //主动抛出异常,一般在方法中使用
}else{
System.out.println(a/b);
}
}
}
运行结果:
分母不能为0!
java.lang.ArithmeticException
at cn.ecut.Exception.Demo4.test(Demo4.java:19)
at cn.ecut.Exception.Demo4.main(Demo4.java:6)
⑤
源代码:
package cn.ecut.Exception;
/**
* 自定义的异常类
*/
public class MyException extends Exception {
//传递数字>13
private int detail;
public MyException(int a){
this.detail=a;
}
public String toString(){
return "MyException{"+detail+'}';
}
}
package cn.ecut.Exception;
public class Test {
public static void main(String[] args) {
try{
test(14);
}catch(MyException e){
System.out.println("Myexception=>"+e);
}
}
static void test(int a) throws MyException{
System.out.println("传递的数为:"+a);
if(a>13){
throw new MyException(a);
}
}
}
运行结果:
传递的数为:14
Myexception=>MyException{14}