java的异常处理
try catch finally
package Test;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a/b);
} catch (Exception e) {
System.out.println("Exception");
} catch (Error e){
System.out.println("Error");
}catch (Throwable t){
System.out.println("Throwable");
}
finally {
System.out.println("是否抛出异常都要执行,用于善后处理工作");
}
}
}
throw 和 throws
package Test;
public class Demo01 {
public static void main(String[] args) {
try {
new Demo01().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println("接收解决方法上的异常");
} finally {
}
}
public void test(int a ,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();
}
System.out.println(a/b);
}
}
自定义异常
package Test;
public class MyException extends Exception{
public int detail;
public MyException( int detail) {
this.detail = detail;
}
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
package Test;
public class Test {
public void test(int b){
if(b>10){
try {
throw new MyException(b);
} catch (MyException e) {
System.out.println("异常超过10");
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Test().test(12);
}
}
package Test;
public class Test {
public static void test(int b) throws MyException {
if(b>10){
System.out.println("异常");
throw new MyException(b);
}
System.out.println("ok");
}
public static void main(String[] args) {
try {
test(12);
} catch (MyException e) {
e.printStackTrace();
}
}
}