Java运行环境就是用异常类Exception的相应子类创建一个异常对象,并等待处理。
异常对象可以调用如下方法得到或输出有关异常的信息:
public String getMessage()、public void printStackTrace()、public String toString()
Java使用try-catch语句来处理异常,将可能出现的异常操作放在try部分。当try部分中的某个语句发生异常后,try部分将立刻结束执行,而转向执行相应的catch部分,所以程序可以将发生异常后的处理放在catch部分。try-catch语句可以有几个catch组成,分别处理发生的相应异常。
1.try-catch语句
try{
//包含可能发生异常的语句
}
catch(ExceptionSubClass1 e){}
catch(ExceptionSubClass2 e){}
各个catch参数中的异常类都是Exception的某个子类,这些子类之间不能有父子关系,否则保留一个含有父类参数的catch即可。
例:
public class TryCatchExample{
public static void main(String args[]){
int m = 0, n = 0, t = 555;
try{
m = Integer.parseInt("8888");// parseInt可以将”数字“格式的字符串,如“234”转化为int型数据
n = Integer.parseInt("abc789");// 发生异常,转向catch
t = 9999;// t没有机会赋值
}
catch (NumberFormatException e){
System.out.println("发生异常:" + e.getMessage());
System.out.println("发生异常:" + e.toString());
e.printStackTrace();
System.out.println("n=" + n );
n = 123;
}
System.out.println("m=" + m + ",n=" + n + ",t=" + t);
}
}
/*输出
发生异常:For input string: "abc789"
发生异常:java.lang.NumberFormatException: For input string: "abc789"
java.lang.NumberFormatException: For input string: "abc789"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:497)
at ch4.TryCatchExample.main(TryCatchExample.java:8)
n=0
m=8888,n=123,t=555
*/
2.自定义异常类
在程序中也可以扩展Exception类定义自己的异常类,然后规定哪些方法产生这样的异常。
一个方法在声明时可以用throws关键字声明要产生的若干个异常类,并在该方法的方法体中具体给出产生异常的操作。
catch的作用就是捕获throw关键字抛出的异常对象。
注:throw是Java关键字,作用是抛出异常,throw和throws是两个不同的关键字。
class NopositiveException extends Exception{
String message;
NopositiveException(int m, int n){
message = "错误:数字" + m + "或" + n + "不是正数";
}
public String toString(){
return message;
}
}
class Computer{
public int getMaxCommonDivisor(int m, int n) throws NopositiveException{
if (n <= 0 || m <= 0){
NopositiveException exception = new NopositiveException(m, n);
throw exception;// 抛出异常,结束方法的执行
}
if (m < n){
int temp = 0;
temp = m;
m = n;
n = temp;
}
int r = m % n;
while (r != 0){
m = n;
n = r;
r = m % n;
}
return n;
}
}
public class ErrorExample{
public static void main(String args[]){
int n = 24, m = 36, result = 0;
Computer computer = new Computer();
try{
result = computer.getMaxCommonDivisor(m, n);
System.out.println(m + "和" + n + "的最大公约数" + result);
m = -12;
n = 22;
result = computer.getMaxCommonDivisor(m, n);//会抛出异常
System.out.println(m + "和" + n + "的最大公约数" + result);
}
catch (NopositiveException e){
System.out.println(e.toString());
}
}
}
/*输出
36和24的最大公约数12
错误:数字-12或22不是正数
*/