Java处理异常---捕获异常

本文深入探讨了Java中的异常处理机制,通过具体示例演示了如何使用try-catch-finally语句来捕获并处理不同类型的异常,如ArithmeticException和NegativeArraySizeException,并解释了异常传播的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法调用过程因为参数传递错误,方法可能会抛出异常对象;用catch接收抛出的异常对象,使用如下方法输出有关异常的信息:

public String getmessage();
public void printDtackTrace();
public String toString();
try-catch-finally语句的综合应用TestException.java
public class TestException {
	public static void test() {
		int[] a =new int[2];
		try {
	    	   int m=Integer.parseInt("1234");
	    	   int n=Integer.parseInt("abcde");//沿调用栈,逐层回溯,找catch
	    	   System.out.println(3/0);//在此之前抛出了异常,故try块自抛出异常,不再向下执行,ArithmeticException
	    	   a[2]=2;//NegativeArraySizeException
	    	   System.out.println("不会被执行!");
	       }
		
		//catch(Exception e) {}//不能在使用Exception的子类之前使用Exception
	    catch(ArithmeticException e) {
	    	e.printStackTrace();
	    }
		catch(NegativeArraySizeException e) {//多个catch,当try中发生异常,会在紧跟的catch后顺序遍历对应的catch
			e.printStackTrace();
		}	
		finally {//catch后跟finally块儿,即使try-catch执行return,finally块儿仍被执行
			System.out.println("finally部分1");//没有catch到异常,但此处可以被执行。
		}
		
	}
	public static void main(String args[]) {
      try{//此处若不处理NumberFormatException,则会将异常抛向JVM,处理效果与此处相同
    	  test();
      }
      catch(NumberFormatException e) {//test函数并未对NumberFormatException做处理,故回溯到调用处进行处理
	    	  System.out.println(e.getMessage());//Exception.getMessage()可以输出错误的详细信息
	    	  //e.printStackTrace();//输出错误信息的另一种形式
	  }
      finally {
			System.out.println("finally部分2");
		}
    }
}

图:java ExceptionClass




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值