一,异常的捕获
语法如下:
1
2
3
4
5
6
7
8
9
10
|
try
{
//程序代码块
}
catch
(Exceptiontype1 e){
}
catch
(Exceptiontype2 e){
}
...
finally
{
}
|
catch关键字后面括号中的Exception类型的参数e.Exception就是try代码块传递给catch代码块的变量类型,e就是变量名。如catch代码块中的语句e.getMessage();
1.getMessage()函数:获得异常的性质。
2.toString()函数:给出异常的类型和性质。
3.printStackTrace()函数:指出异常的类型,性质,栈层次及出现在程序中的位置。
在完整的异常处理语句一定要包含finally语句,不管程序有无异常发生,并且不管try-catch之间的语句是否顺利执行完毕,都会执行finally语句。除了以下4种特殊情况:
1.在finally语句块中发生了异常;2.在前面的代码中用了System.exit()退出程序;3.程序所在的线程死亡;4.关闭了CPU
例子1:捕获单个异常:捕获加载空异常时发生的异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package
com.lixiyu;
public
class
CatchException {
public
static
void
main(String[] args){
try
{
System.out.println(
"进入try语句块"
);
Class<?>clazz=Class.forName(
""
);
//得到一个空的Class对象
System.out.println(
"离开try语句块"
);
}
catch
(ClassNotFoundException e){
System.out.println(
"进入catch语句块"
);
e.printStackTrace();
System.out.println(
"离开catch语句块"
);
}
finally
{
System.out.println(
"进入finally语句块"
);
}
}
|
例子2:捕获多个异常:对加载数据库驱动和创建数据库连接时所发生的异常分别进行捕获
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package
com.lixiyu;
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.SQLException;
public
class
CatchExceptionOne {
private
static
String URL=
"jdbc:mysql://localhost:3306/db_database"
;
private
static
String DRIVER=
"com.mysql.jdbc.Driver"
;
private
static
String USERNAME=
"mr"
;
private
static
String PASSWORD=
"mingri"
;
private
static
Connection conn;
public
static
Connection getConnection(){
try
{
Class.forName(DRIVER);
//加载驱动程序
conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
//建立连接
return
conn;
}
catch
(ClassNotFoundException e){
//捕获类为发现异常
e.printStackTrace();
}
catch
(SQLException e) {
// 捕获SQL异常
e.printStackTrace();
}
return
null
;
}
public
static
void
main(String[] args){
CatchExceptionOne.getConnection();
}
}
|
二,异常的抛出
1.使用throws声明抛出异常
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package
com.lixiyu;
public
class
Shoot {
static
void
pop()
throws
NegativeArraySizeException{
//定义方法并抛出NegativeArraySizeException异常
int
[]arr=
new
int
[-
3
];
}
public
static
void
main(String[] args){
try
{
pop();
}
catch
(NegativeArraySizeException e){
System.out.println(
"pop()方法抛出的异常"
);
}
}
}
|
2.使用throw语句抛出异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package
com.lixiyu;
public
class
UseThrow {
final
static
double
PI=
3.14
;
public
void
computerArea(
double
r)
throws
Exception{
if
(r<=
0.0
){
throw
new
Exception(
"程序异常:\n半径"
+r+
"不大于0."
);
//使用throw语句抛出异常
}
else
{
double
circleArea=PI*r*r;
System.out.println(
"半径是"
+r+
"的圆面积是:"
+circleArea);
}
}
public
static
void
main(String[] args){
UseThrow ut=
new
UseThrow();
try
{
ut.computerArea(-
200
);
}
catch
(Exception e){
System.out.println(e.getMessage());
}
}
}
|
本文转自lixiyu 51CTO博客,原文链接:http://blog.51cto.com/lixiyu/1307676,如需转载请自行联系原作者