Java学习之异常

简介

《Java语言导读》中对于异常的定义时这样的:异常是在程序执行期间中断指令的正常流程的事件。这些异常可能是用户错误引起的,有的是程序错误引起的,还有一些是因为物理错误引起的。

当一个方法在执行过程中发生错误时,该方法会创建一个包含错误信息的对象,并把它交给运行时系统。该对象就被称为异常对象。异常对象包含的错误信息包括错误的类型和错误发生时程序的状态。创建异常对象并把它交给运行时系统的过程称为抛出异常

异常的分类

  1. 检查性异常(非运行时异常):最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。比如语法语法错误等,这些异常在编译时不能被简单地忽略,但是较为容易解决。
  2. 运行时异常:运行时异常是可能被程序员避免的异常,是程序运行过程中产生的异常,具有不确定性。与检查性异常相反,运行时异常可以在编译时被忽略。
  3. 错误:错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。

Exception类的层次

在这里插入图片描述
这里展示一下Throwable类的主要方法:
在这里插入图片描述

捕获异常

可以使用try/catch进行异常捕获。try/catch代码块放在异常可能发生的地方。

try{
	//程序代码
}catch()
{
	//Catch块
}

Catch 语句包含要捕获异常类型的声明。当保护代码块中发生一个异常时,try 后面的 catch 块就会被检查。如果发生的异常包含在 catch 块中,异常会被传递到该 catch 块,这和传递一个参数到方法是一样。
举例:

public class ExcepTest {
    public static void main(String args[]){
        try {
            int a[]=new int[2];
            System.out.println("Access elements three :"+a[3]);
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("Exception thrown :"+e);
        }
        System.out.println("Out of the block");
    }
}

结果如下:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
多重捕获块

一个try代码块中可能存在多个异常需要捕捉,这个时候就可以跟随多个catch代码块。

try{
   // 程序代码
}catch(异常类型1 异常的变量名1){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}

发生异常时,会逐一被各catch捕捉,查看该异常是否符合自己的异常类型,如果是,则执行。

throws/throw关键字

如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明。throws 关键字放在方法签名的尾部。

也可以使用 throw 关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。

import java.io.*;
public class className
{
  public void deposit(double amount) throws RemoteException
  {
    // Method implementation
    throw new RemoteException();
  }
  //Remainder of class definition
}

一个 方法可以抛出多个异常,多个异常之间用逗号隔开。

import java.io.*;
public class className
{
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
       // Method implementation
   }
   //Remainder of class definition
}
finally关键字

finally 关键字用来创建在 try 代码块后面执行的代码块。无论是否发生异常,finally 代码块中的代码总会被执行。在 finally 代码块中,可以运行清理类型等收尾善后性质的语句。finally 代码块出现在 catch 代码块最后,语法如下:

public class ExcepTest{
  public static void main(String args[]){
    int a[] = new int[2];
    try{
       System.out.println("Access element three :" + a[3]);
    }catch(ArrayIndexOutOfBoundsException e){
       System.out.println("Exception thrown  :" + e);
    }
    finally{
       a[0] = 6;
       System.out.println("First element value: " +a[0]);
       System.out.println("The finally statement is executed");
    }
  }
}

运行结果如下:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

注意

  1. catch 不能独立于 try 存在。
  2. 在 try/catch 后面添加 finally 块并非强制性要求的。
  3. try 代码后不能既没 catch 块也没 finally 块。
  4. try, catch, finally 块之间不能添加任何代码。

声明自定义异常

声明一个自定义异常主要注意:

  • 所有异常都必须是 Throwable 的子类。
  • 如果希望写一个检查性异常类,则需要继承 Exception 类。
  • 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。

可以参考如下例子:

/**
 * 自定义异常处理器,继承Exception或者RuntimeException,依情况而定.
 * @author erqing
 *
 */
public class NameNotSupportException extends RuntimeException {
 
	private static final long serialVersionUID = 7295869280641332966L;
 
	public NameNotSupportException() {
	}
 
	public NameNotSupportException(String message) {
		super(message);
	}
}

public class DefineTest {
 
	public static void main(String[] args) {
		String name = "egg";
		if(!"erqing".equals(name)){
			throw new NameNotSupportException("erqing");
		}else{
			System.out.println("name is OK!");
		}
	}
}

运行结果:

Exception in thread "main" NameNotSupportException: erqing
	at DefineTest.main(DefineTest.java:7)

参考资料:
http://blog.csdn.net/zhangerqing/article/details/8248186
http://www.runoob.com/java/java-exceptions.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值