java的异常处理

java将如何处理异常

java 通过面向对象的方法进行异常处理,把各种不同的异常进行分类,并提供了良好的接口。
在java中,每个异常都是一个对象,它是Throwable类或其他子类的实例。
当一个方法出现异常后便抛出一个异常,该对象中包含有异常信息,调用这个对象的方法可以捕获到这个异常并进行处理。
java的异常处理是通过5个关键词来实现的:try、catch、throw、throws和finally。

package am;
/**
 * 
 * 语法结构
 *
 */

public class Test4 {

	public static void main(String[] args) {
		try{
			//可能处出现异常的代码块
		}catch(Exception e){
			//Exception 或 子类,处理异常
		}finally{
			//无论是否出现异常,都必须执行的代码块,finally不是必须存在的
		}
	}

}
package am;
/**
 * 如何处理异常
 * try 用来定义可能出现异常的代码块
 * 
 * catch 用来捕捉异常,处理异常
 *
 */

public class Test2 {

	public static void main(String[] args) {

		System.out.println("hello1");
		System.out.println("hello2");
		try{
			int a = 10;
			int b = a/0;
		}catch(ArithmeticException e ){
			System.out.println("保险公司报销");
		}
		System.out.println("hello3");
		System.out.println("hello4");
		try{
			System.out.println("hello5");
			System.out.println("hello6");
			String str = null;
			System.out.println(str.charAt(2));
		}catch(NullPointerException e){
			System.out.println("第二个异常被处理掉");
		}
		System.out.println("hello7");
		
		
	}

}

package am;
/**
 * 如何处理异常
 * try 用来定义可能出现的异常的代码块
 * catch 用来捕捉异常,处理异常
 * finally 无论是否出现异常,都必须执行的代码块,一般用来关闭连接,释放流
 * 
 * 
 * 
 *
 */

public class Test3 {

	public static void main(String[] args) {
		System.out.println("hello1");
		System.out.println("hello2");
		System.out.println("hello3");
		try{
			int a = 10;
			int b = a/0;
		}catch(ArithmeticException a){
			System.out.println("保险公司报销");
		}finally{
			System.out.println("我和咖啡");
		}
		System.out.println("hello4");
		System.out.println("hello5");
		try{
			System.out.println("hello6");
			System.out.println("hello7");
			String str = null;
			System.out.println(str.charAt(5));
		}catch(NullPointerException a){
			System.out.println("第二个异常");
		}finally{
			System.out.println("我继续喝咖啡");
		}
	
		System.out.println("hello8");

		
	}

}

package am;
/**
 * try 不能独立存在
 * catch 不能独立存在
 * finaly 不能独立存在
 * 
 * try 后面可以直接写finally  ;finally 可以不存在
 * 
 * try中可以有继续try;catch中可以有继续try;finally中可以有继续try
 *
 *
 */

public class Test6 {

	public static void main(String[] args) {

		try{
			try{
				
			}catch(Exception e){
				
			}
		}catch(Exception e){
			try{
				
			}catch(Exception a){
				
			}
		}finally{
			try{
				
			}catch(Exception a){
				
			}
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值