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){
}
}
}
}