【Java开源代码栏目提醒】:网学会员鉴于大家对Java开源代码十分关注,论文会员在此为大家搜集整理了“TextFinally.java”一文,供大家参考学习
package com.zf.s9;//创建一个包
public class TextFinally {//操作finally的类
public static double getSqrt(String nStr) throws CommonException,
ThrowException {// 计算平方根
if (nStr == null) {
throw new CommonException("输入的字符串不能为空!");
}
double n = 0;
try {
n = Double.parseDouble(nStr);
} catch (NumberFormatException e) {
throw new CommonException("输入的字符串必须能够转化成数字!");
}
if (n < 0) {
throw new ThrowException("输入的字符串转化成的数字必须大于等于0!");
}
return Math.sqrt(n);
}
public static double mustConvertInt(String str) {//验证输入的字符串必须能够转化为数字
try {
System.out.println("Try块!");
return getSqrt(str);
} catch (CommonException e1) {// 捕获异常
System.out.println("捕获 CommonException 异常!");
System.out.println("异常: " + e1.getMessage());
return -1;
} catch (ThrowException e2) {// 捕获异常
System.out.println("捕获 ThrowException 异常!");
System.out.println("异常: " + e2.getMessage());
return -2;
} finally {// 内容总执行
System.out.println("内容总执行,可释放资源");
}
}
@SuppressWarnings("finally")
public static double numGreaterthanZero(String str) {//转化成的数字必须>=0
try {
System.out.println("Try块!");
return getSqrt(str);
} catch (CommonException e1) {// 捕获异常
System.out.println("捕获 CommonException 异常!");
System.out.println("异常: " + e1.getMessage());
return -1;
} catch (ThrowException e2) {// 捕获异常
System.out.println("捕获 ThrowException 异常!");
System.out.println("异常: " + e2.getMessage());
return -2;
} finally {// 内容总执行
System.out.println("内容总执行,可释放资源");
return 0;
}
}
public static void main(String[] args) {//java程序主入口处
System.out.println("1.输入的字符串必须能够转化成数字");
System.out.println("未发生异常时输出:");
mustConvertInt("12");
System.out.println("发生异常时输出:");
mustConvertInt("aa");
System.out.println("2.输入的字符串转化成的数字必须大于等于0");
System.out.println("未发生异常时输出:");
numGreaterthanZero("3");
System.out.println("发生异常时输出:");
numGreaterthanZero("-3");
}
}
上一篇:
TextFileViewer.java
下一篇:
其它计算机论文:探究计算机基础教育教学的策略