异常处理
异常(Exception)
错误(ERROR)
捕捉异常
public class 捕捉异常 {
public static void main(String[] args) {
System.out.println("==========已处理异常==========");
try {
System.out.println(10/0);
} catch (Error e) {
System.out.println("Error");
}
catch (Exception e){
e.printStackTrace();
System.out.println("Exception");
}
catch (Throwable t){
System.out.println("异常");
System.out.println("Throwable");
}finally
{
System.out.println("finally");
System.exit(1);
}
}
}
抛出异常
public class 抛出异常 {
public static void main(String[] args) {
int b = 0;
try {
if (b == 0) {
throw new ArithmeticException();
}
} catch (Exception e) {
}
new 抛出异常().ff(1,0);
}
public void ff(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException();
}
}
}
自定义异常
public class 自定义异常 extends Exception{
private int detail;
public 自定义异常(int detail) {
this.detail=detail;
}
@Override
public String toString() {
return "自定义异常{" +
"detail=" + detail +
'}';
}
}
public class Test {
static void test(int a)throws 自定义异常{
System.out.println("传递的参数:"+a);
if (a>10){
throw new 自定义异常(a);
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
}catch (自定义异常 e){
System.out.println("自定义异常>>>>>>"+e);
}
}
}