import java.util.InputMismatchException;
import java.util.Scanner;
public class TestException {
public static void main(String[] args) {
int a = 1;
int b = 0;
try
{
// 如果不用try-catch程序就不会往下执行了
if (b == 0) throw new ArithmeticException();
System.out.println("a/b的值是:" + a / b);
System.out.println("this will not be printed!");
} catch (ArithmeticException e) {
System.out.println("程序异常,变量b不能为0!" + e);
}
//多重catch语句,必须先小后大,先父类在子类 。否则,捕获底层异常类的catch子句将可能会被屏蔽。
Scanner input = new Scanner(System.in);
try {
System.out.println("请输入第一个数:");
int one = input.nextInt();
System.out.println("请输入第二个数");
int two = input.nextInt();
System.out.println("两数相除结果为:" + one / two);
} catch (InputMismatchException e) {
System.out.println("请输入整数");
} catch (ArithmeticException e) {
System.out.println("two不能为0");
} catch (Exception e) {
System.out.println("未知错误");
}
//try嵌套
try {
int c = 0;//为0抛出ArithmeticException 为1抛出为0抛出ArithmeticException
int d = 42 / c;
System.out.println("c=" + c);
try {
if (c == 1) {
c = c / (c - c);
}
if (c == 2) {
int e[] = {1};
e[42] = 99;
}
} catch (ArrayIndexOutOfBoundsException e) {
//数组超出异常
System.out.println("数组超出异常" + e);
}
} catch (ArithmeticException e) {
System.out.println("c不能为0");
}
//throw
//该程序两次处理相同的错误,首先,main()方法设立了一个异常关系然后调用proc()。
// proc()方法设立了另一个异常处理关系并且立即抛出一个NullPointerException实例,
// NullPointerException在main()中被再次捕获。
try {
proc();
} catch (NullPointerException e) {
System.out.println("内部捕获"+e);
}
//finally 在try/catch块完成之后另一个try/catch出现之前执行
try{
proc1();
}catch (Exception e){
System.out.println("捕获异常");
}
//自定义异常
try{
compute(1);
compute(20);
}catch(MyException me){
System.out.println("捕获 " + me);
}
System.out.println("程序正常结束。");
}
static void proc() {
try {
throw new NullPointerException("空指针异常");
} catch (NullPointerException e) {
System.out.println("捕获异常" + e);
throw e;
}
}
static void proc1(){
try{
System.out.println("内部异常");
throw new RuntimeException("运行时异常");
}finally {
System.out.println("finally执行");
}
}
static void compute(int a) throws MyException{
System.out.println("compute方法(" + a + ")");
if(a > 10){
throw new MyException(a);
}
System.out.println("正常退出!");
}
}
class MyException extends RuntimeException{
private int code;
MyException(int a){
this.code=a;
}
@Override
public String toString() {
return "MyException{"+code+"}";
}
}
帮助理解java异常的简单例子
最新推荐文章于 2023-05-12 18:13:33 发布