第6章异常的捕获及处理
| 工作总结 | 商务报告 | 项目展示| 商务展示 |
public class ExceptionDemo02{
public static void main(String }catch(Exception e){
("出现异常了:" + e) ;
}finally{
closeDB( );
}
12
直接打印异常类对象:(e) ;
使用Exception类提供的一个方法:printStackTrace( )
(注:开发中常用,打印异常的堆栈信息)
public class ExceptionDemo05{
public static void main(String args[]){
("****** 计算开始 ********") ;
int i = 10 ;
int j = 0 ;
try{
int temp = i / j ; // 此处产生了异常
("相除的结果:" + temp) ;
}catch( Exception e){
e. printStackTrace( );
}
("******* 计算结束 *********") ;
}
}
13
、throw
throws:如果一个方法引发了异常,但该方法本身并不对这个异常进行处理,而是交给被调用处处理。那么该方法就要用throws关键字来声明。
例:public int div( int i , int j ) throws Exception{
不含处理异常语句 ;
}
14
class Math{ //定义除法类
public int div( int i , int j ) {
int temp = i / j ; //此处有可能出现异常
return temp ;
}
}
public class ThrowsDemo{
public static void main(String args[]){
Math m = new Math( ) ; // 实例化Math类对象
("除法操作:" + ( 10 , 0 )) ;
}
}
throws Exception
try{
}
catch( Exception e){
( ) ; // 打印异常
}
、throw
throw:有2个功能
⑴Java中异常处理是分层次的,throw可以把捕获到的异常抛
到上一层,由上一层进行异常处理。
格式:throw 异常类对象;
⑵以前处理的异常都是由系统(JVM)自动实例化的,不用new.
现在,可以使用throw关键字在方法中手动抛出一个异常。
class Math{
public int div(int i , int j) {
int temp = 0 ;
try{
int temp = i / j ; //此处有可能出现异常
}catch ( Exception e){
throw e ;
}
return temp ;
}
}
public class ThrowDemo02{
public static void main(String args[]){
Math m = new Math( ) ;
try{
("除法操作:" + (10,0)) ;
}catch(Exception e){
("异常产生:" + e) ;
}
}
}
public class ThrowDemo01{
public sta
第6章异常的捕获及处理 来自淘豆网www.taodocs.com转载请标明出处.