Error:
Exception:
在Exception分支中有一个重要的子类RuntimeException (运行时异常)
这些异常一般是由程序逻辑错误引起的, 程序应该从逻辑角度尽可能避免这类异常的发生;
Error和Exception的区别: Error通常是灾难性的致命的错误,是程序无法控制和处理的,当 出现这些异常时,Java虛拟机(JVM) 一般会选择终止线程; Exception通常情况下是可以被系统处理的,并且在程序中应该尽可能的去处理这些异常
抛出异常和捕获异常
异常处理的五个关键字:
捕获异常
//比如说下面这个异常:
public class Test {
public static void main(String[] args) {
int a=1;
int b=0;
System.out.println(a/b);
}
}
异常:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at src.com.exception.Test.main(Test.java:7)
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 {//最后处理善后工作(无论是否出异常,finally都会被执行),这里可以不写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监控区域
System.out.println(a/b);
}catch (Error e){
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}finally {
System.out.println("finally");
}
}
}
输出:
Exception
finally
public class Test2 {
public static void main(String[] args) {
int a=1;
int b=0;
//选中“ System.out.println(a/b);”后,快捷键:Ctrl+alt+T
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace(); //打印错误的栈信息
}
}
}
输出:
java.lang.ArithmeticException: / by zero
at src.com.exception.Test2.main(Test2.java:9)
public class Test {
public static void main(String[] args) {
int a=1;
int b=0;
//假设要捕获多个异常,要从小到大递进。
try {
if(b==0){ //主动抛出异常,throw。
throw new ArithmeticException();
}
System.out.println(a/b);
}catch (Exception e){
System.out.println("Exception");
}finally {
System.out.println("finally");
}
}
}
public class Test {
public static void main(String[] args) {
try {
new Test().test(1, 0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设这个方法中处理不了这个异常。方法上抛出异常(throws)
public void test(int a, int b) throws ArithmeticException{
if (b == 0) {
throw new ArithmeticException();//主动抛出异常,一般在方法中使用(throw)
}
}
}
使用Java内置的异常类可以描述在编程时出现的大部分异常情况。除此之外,用户还可以自定义异常。用户自定义异常类,只需继承Exception类即可。
在程序中使用自定义异常类,大体可分为以下几个步骤:
//自定义的异常类
public class MyException extends Exception{
//传递数字>10
private int detail;
public MyException(int a) {
this.detail = a;
}
//toString:异常的打印信息
@Override
public String toString() {
return "MyException{" + detail + ‘}‘;
}
}
public class Test {
static void test(int a) throws MyException {
System.out.println("传递的参数为:"+a);
if(a>10){
throw new MyException(a);//抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
//这里还可以增加一些处理异常的代码块
System.out.println("MyException=>"+e);
}
}
}
输出(根据传递的参数不同,结果就不同):
传递的参数为:1
OK
==========
传递的参数为:11
MyException=>MyException{11}
原文:https://www.cnblogs.com/fxliyh/p/14548656.html