Java面向对象(六)
Java异常处理
1.try...catch和finally
语法:
try{
//可能发生异常的语句
}catch(Exception类或其子类){
//对异常进行捕获并做出相应处理
}
举例:
public class Page141 {
public static int divide(int x,int y){
try{ //try中放可能发生异常的语句
int result=x/y;
return result;
}catch(Exception e){ //对异常进行捕获并做出相应处理
System.out.println("捕获的异常为:"+e.getMessage()); //返回异常信息
}
return -1;
}
public static void main(String[] args) {
int result=divide(4,0);
if(result==-1){
System.out.println("发生异常");
}else{
System.out.println(result);
}
}
}
此时catch(){}处理完异常后仍会继续向下执行,不会因为异常而终止
有时希望有些语句无论是否异常都要执行,这时就可以在try...catch后加上finally{}代码块,finally{}代码块不受return语句和异常影响
举例:
public class Page141 {
public static int divide(int x,int y){
try{ //try中放可能发生异常的语句
int result=x/y;
return result;
}catch(Exception e){ //对异常进行捕获并做出相应处理
System.out.println("捕获的异常为:"+e.getMessage());
}finally{
System.out.println("执行finally代码块");
}
return -1;
}
public static void main(String[] args) {
int result=divide(4,0);
if(result==-1){
System.out.println("发生异常");
}else{
System.out.println(result);
}
}
}
2.throws关键字
有些时候,方法代码中是否会出现异常开发者并不明确或不急于处理,Java允许将异常从当前方法中抛出,让后续调用者在使用时再进行异常处理。
语法:
[修饰符] 返回值类型 方法名([参数类型 参数名]...) throws 异常类1,异常类2,...{
//方法体
}
举例:
public class Page143 {
public static int divide(int x,int y) throws Exception {
int result=x/y;
return result;
}
public static void main(String[] args) {
try{
int result=divide(4,0);
System.out.println(result);
}catch (Exception e){
System.out.println("捕获的异常信息为:"+e.getMessage());
}
}
}
3.throw关键字
throw关键字也可以抛出异常,但throw用于方法体内,并且抛出的是一个异常类对象,而throws用于方法声明中,用来指明方法可能抛出多个异常
语法:
[修饰符] 返回值类型 方法名([参数类型 参数名]...) throws 异常类1,异常类2,...{
//方法体
throw new Exception 类或其子类构造方法
}
举例:
public class Page146 {
public static void printAge(int age) throws Exception {
if(age<=0){
throw new Exception("年龄有误,必须是正整数");
}else {
System.out.println("年龄为:"+age);
}
}
public static void main(String[] args) {
int age=-3;
try{
printAge(age);
}catch(Exception e){
System.out.println("捕获的异常为:"+e.getMessage());
}
}
}
age为负数显然也能通过编译,但它却是不符合实际意义的,因此再程序中对age进行判断,对于不合法的输入用throw抛出异常并指定异常提示信息,同时继续使用throws对抛出的异常进行处理
4.自定义异常
Java中定义了大量的异常类,可以描述编程时出现的大部分异常情况,但有时可能需要描述程序中特有的异常情况。Java允许用户自定义异常,但自定义的异常类必须继承自Exception类或其子类。
举例:
class DivideByMinusException extends Exception{
public DivideByMinusException(){
super();
}
public DivideByMinusException(String message){
super(message);
}
}
public class Page147 {
public static int divide(int x,int y) throws DivideByMinusException{
if(y==0){
throw new DivideByMinusException("除数是0");
}else{
int result=x/y;
return result;
}
}
public static void main(String[] args) {
try{
int result=divide(4,0);
System.out.println("结果:"+result);
}catch(DivideByMinusException d){
System.out.println("捕获的异常为:"+d.getMessage());
}
}
}