在上一篇文章(java中的异常处理基础)中,我们讨论了可以使用以下五个关键字在您的程序中实现异常处理:
1)try
该try块包含了一系列内有可能产生异常的程序语句。在try块之后始终是catch块,该catch块捕获在try块发生的异常。
语法:try{
//代码块以监视错误
}
2)catch()
一个catch块始终与相关try块。它捕获程序执行过程中try块引发的错误。它包含Exception类类型的对象。在程序执行过程中发生的错误会生成一个特定的对象,该对象具有有关程序中发生的错误的信息。
语法:try {
//代码块以监视错误
}
catch (ExceptionType1exOb) {
//ExceptionType1的异常处理程序
}
catch (ExceptionType2 exOb) {
//ExceptionType2的异常处理程序
}
在以下示例代码中,您将看到如何在Java程序中完成异常处理。
本示例读取变量a和b的两个整数。如果输入除数字(0-9)以外的任何其他字符,则NumberFormatException对象将捕获错误。之后,ex.getMessage()打印有关错误发生原因的信息。
考虑一下程序:import java.io.*;
public class ExceptionHandle
{
public static void main(String[] args) throws Exception
{
try{
int a,b;
DataInputStream in = new DataInputStream(System.in);
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage()
+ " is not a numeric value.");
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
}
3)throw关键字
throw语句导致Java代码的正常控制流终止,并停止throw语句之后的后续语句的执行。
以前,您只捕获JRE系统引发的异常。但是,您的程序可以使用throw语句显式地引发异常。抛出的一般形式如下所示:
throw ThrowableInstance;
我们仅将throw关键字与对象引用一起使用即可引发异常。throw语句需要一个参数,即一个throwable对象。
看以下程序:import java.util.*;
class ExceptionThrow
{
public static void main(String arg[])
{
try{
Scanner KB=new Scanner(System.in);
System.out.print("Enter Percentage:");
int per=KB.nextInt();
if(!(per>=0 && per<=100))
{
throw(new Exception("Invalid Percentage...."+per));
}
else
{
System.out.println("Valid Percentage...");
}
}catch(Exception e){
System.out.println(e);
}
}
}