捕获和抛出异常

异常处理五个关键字:try 、catch 、 finally 、 throws

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) {//catch(想要捕获的异常类型)捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally {
//finally一般是用来处理善后工作的,可以不用
//假设之后学到IO流,资源关闭,一般放在finally
System.out.println("finally");
}
}
===========================================================
package com.exception;

public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域
new Test().a();
System.out.println(a/b);
} catch (Throwable e) {//catch捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally {
//finall一般是用来处理善后工作的,可以不用
//假设之后学到IO流,资源关闭,一般放在finally
System.out.println("finally");
}
}
public void a(){b();}
public void b(){a();}
}

=======================================================================
package com.exception;

public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域
/* new Test().a();*/
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 {
//finall一般是用来处理善后工作的,可以不用
//假设之后学到IO流,资源关闭,一般放在finally
System.out.println("finally");
}
}
public void a(){b();}
public void b(){a();}
}
=================================================================
package com.exception;

public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域
/* new Test().a();*/
if (b==0){
//throw throws
throw new ArithmeticException();//主动抛出异常,一般在方法里使用
}



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 {
//finall一般是用来处理善后工作的,可以不用
//假设之后学到IO流,资源关闭,一般放在finally
System.out.println("finally");
}
}
=================================================================

package com.exception;

public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//快捷键ctrl+alt+t
try {
System.out.println(a/b);
} catch (Exception e) {
System.exit(1);//手动关闭程序
e.printStackTrace();//打印错误的栈信息
} finally {
}
}
}
===================================================================
package com.exception;

public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
//假如这不加trycatch,就会自动停止。
//有些错误是意料中,又不想让程序停止,就可以加trycatch让程序继续进行
new Test().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设这方法中,处理不了这个异常,在方法上抛出异常是throws
public void test(int a , int b)throws ArithmeticException{
if (b==0){
//throw throws
//主动抛出异常是throw
throw new ArithmeticException();//主动抛出异常,一般在方法里使用
}
System.out.println(a/b);
}
}
===========================================================================
上一篇:PE文件解析_Dos头


下一篇:Linux bzip2 命令