try(监控代码异常) catch(捕获相应的异常并处理) finally(无论如何都会执行)
选中代码 CTRL+alt+T (intelliJ IDEA) 快速选中try...catch
package hk.exception;
public class Exception {
public static void main(String[] args) {
try{
System.out.println(1/0);
}catch(ArithmeticException e){
System.out.println("exception:分母为0");
}finally {
System.out.println("结束");
}
try{
System.out.println(1/1);
}catch(ArithmeticException e){
System.out.println("exception:分母为0");
}finally {
System.out.println("结束");
}
}
}
e.printStackTrace(); 打印错误的栈信息
public static void main(String[] args) {
try{
System.out.println(1/0);
}catch(ArithmeticException e){
e.printStackTrace();
}finally {
System.out.println("结束");
}
}
catch可以捕获多个异常 一般自上而下异常范围递增或者不变
有点switch的感觉,发现一个异常就跳出结束
package hk.exception;
public class Exception {
public static void main(String[] args) {
try{
System.out.println(1/0);
f1();
}catch(ArithmeticException e){
e.printStackTrace();
System.out.println("e");
}catch (StackOverflowError e1){
System.out.println("StackOverflowError");
System.exit(1);
}
finally {
System.out.println("结束");
}
}
public static void f1(){
f2();
}
public static void f2(){
f1();
}
}
package hk.exception;
public class Exception {
public static void main(String[] args) {
try{
f1();
System.out.println(1/0);
}catch(ArithmeticException e){
e.printStackTrace();
System.out.println("e");
}catch (StackOverflowError e1){
System.out.println("StackOverflowError");
}
finally {
System.out.println("结束");
}
}
public static void f1(){
f2();
}
public static void f2(){
f1();
}
}
throw throws 主动抛出异常
一般在方法中使用
package hk.exception;
public class Exception {
public static void main(String[] args) {
int a = 10;
int b = 0;
division(a,b);
}
public static void division(int a,int b){
try {
if (b==0){
throw new ArithmeticException();
}
//System.out.println(a/b);
}finally {}
}
}
自定义异常 继承Exception
package hk.exception;
public class TextException extends java.lang.Exception {
private int detail;
public TextException(int a){
this.detail=a;
}
@Override
public String toString() {
return "Text{" +
"detail=" + detail +
'}';
}
}
package hk.exception;
public class Application {
public static void f(int a)throws TextException {
System.out.println("a参数:"+a);
if (a>10){
throw new TextException(a);
}
System.out.println("OK");
}
public static void main(String[] args) {
try{
f(10);
}catch (TextException e){
System.out.println("Text ERROR\n"+e);
}
try{
f(11);
}catch (TextException e){
System.out.println("Text ERROR\n"+e);
}
}
}