1、如何抛出异常
抛出异常使用throws/throw关键字。了解异常看这里:什么是java中的异常
想知道如何捕获异常看这里:如何捕获异常
2、throws关键字是什么
throws 用来声明某一个方法可能抛出的异常,这个异常可以是系统定义的,也可以是自己定义的。调用throws修饰的方法,必须要对其做异常处理,或者将异常声明抛出(使用throws)。
语法:
- import java.io.*;
- public class className
- {
- public void deposit(double amount) throws RemoteException
- {
- // Method implementation
- }
- //Remainder of class definition
- }
语法:
- import java.io.*;
- public class className
- {
- public void withdraw(double amount) throws RemoteException,
- InsufficientFundsException
- {
- // Method implementation
- }
- //Remainder of class definition
- }
- import java.io.*;
- public class ExceptionTest{
- public static void main(String args[]) throws IOException, NullPointerException{
- file = new FileInputStream(fileName);
- x = (byte) file.read();
- }
- }
Exception in thread "main" Java.io.FileNotFoundException: /usr/test (No such file or directory)
at java.io.FileInputStream.open(Native Method)异常被抛出,中断执行,并打印了堆栈信息。
3、throw关键字是什么
使用throw关键字可以抛出一个异常对象。另外,如果一个方法不处理异常,则该方法必须使用throws关键字声明它。
语法:
- import java.io.*;
- public class className
- {
- public void deposit(double amount) throws RemoteException
- {
- // Method implementation
- throw new RemoteException();
- }
- //Remainder of class definition
- }
- public class className
- {
- public void main(String[] args) throws Exception
- {
- throw new Exception("异常");
- }
- }
Exception in thread "main" java.lang.Exception: 异常
at com.test.Test.main(Test.java:37)
异常被抛出,并打印了堆栈信息。
4、throws/throw关键字有什么区别
throws是用来声明一个方法可能抛出的所有异常信息。throw则是指抛出的一个具体的异常对象。
原文地址:http://blog.csdn.net/ooppookid/article/details/51100373