一、什么是异常处理?
在程序运行过程中,可能会有一些逻辑错误,比如一个数除以0,这时候就发生了异常。你可以不处理异常,那么程序就会崩溃,后面的内容都无法运行。
例如:
package test;
public class HelloWorld {
public static void main(String[] args){
int result = divide(4,0);
System.out.println(result);
}
public static int divide(int x, int y){
int result = x / y;
return result;
}
}
程序运行结果为:
Exception in thread “main” java.lang.ArithmeticException: / by zero
at test.HelloWorld.divide(HelloWorld.java:10) at
test.HelloWorld.main(HelloWorld.java:5)
这个时候程序因为除以0发生了异常,后面的代码无法继续运行。
如果我们想程序能够处理异常并继续运行,可以通过try…catch语法来对异常进行处理:
package test;
public class HelloWorld {
public static void main(String[] args){
try{
int result = divide(4,0);
System.out.println(result);
}catch (Exception e){
System.out.println("捕获到异常:" + e.getMessage());
System.out.println("处理该异常....");
}
System.out.println("程序继续执行");
}
public static int divide(int x, int y) {
int result = x / y;
return result;
}
}
运行结果为:
捕获到异常:/ by zero
处理该异常….
程序继续执行
这个时候,我们可以捕获到这个异常,并进行一定的修复处理。try后面的代码不会继续运行,但是其它后面的语句可以继续运行。这样就不会因为有异常产生而导致程序强制结束。
二、finally关键字
此外,如果异常发生或者异常没发生都有一些代码要执行的话(如释放资源),那么可以通过finally关键字完成:
package test;
public class HelloWorld {
public static void main(String[] args){
try{
int result = divide(4,0);
System.out.println(result);
}catch (Exception e){
System.out.println("捕获到异常:" + e.getMessage());
System.out.println("处理该异常....");
}finally{
System.out.println("无论是否异常,释放资源...");
}
System.out.println("程序继续执行");
}
public static int divide(int x, int y) {
int result = x / y;
return result;
}
}
三、throws关键字
如果divide是别人写的函数,我们通常情况不会去看divide函数的实现,但是divide函数确实会发生异常。针对这种情况,我们可以使用throws关键字来为函数声明它会抛出异常:
package test;
public class HelloWorld {
public static void main(String[] args){
try{
int result = divide(4,0);
System.out.println(result);
}catch (Exception e){
System.out.println("捕获到异常:" + e.getMessage());
System.out.println("处理该异常....");
}finally{
System.out.println("无论是否异常,释放资源...");
}
System.out.println("程序继续执行");
}
public static int divide(int x, int y) throws Exception {
int result = x / y;
return result;
}
}
如果有throws关键字,就说明这个函数要求使用者提供异常处理。如果使用者没有实现异常处理,那么编译的时候就会给出错误:
Exception in thread “main” java.lang.Error: Unresolved compilation
problem: Unhandled exception type Exception
四、自定义异常
为了描述程序中特有的异常情况,你也可以继承Exception类来实现自己的异常类:
package test;
public class HelloWorld {
public static void main(String[] args){
try{
int result = divide(4,-1);
System.out.println(result);
}catch (Exception e){
System.out.println("捕获到异常:" + e.getMessage());
System.out.println("处理该异常....");
}finally{
System.out.println("无论是否异常,释放资源...");
}
System.out.println("程序继续执行");
}
public static int divide(int x, int y) {
if(y<0){
throw new DivideByMinusException("被除数是负数");
}
int result = x / y;
return result;
}
}
class DivideByMinusException extends Exception{
public DivideByMinusException(){
super();
}
public DivideByMinusException(String message){
super(message);
}
}