参考下面的程序,试修改程序,捕获相关异常,使得程序能正常运行。[提示:用错误数据测试,即可得到异常类名,运行时主方法参数输入 abc 测试]
public class StringIndexOutOf {
public static void main(String args[]) {
System.out.println(“字符串索引越界异常”);
String str=args[0];
System.out.println(“第四个字符为”+str.charAt(3));
int aa=Integer.parseInt(args[0]);
System.out.println(“平方为”+aa*aa);
}
}
文件名:StringIndexOutOf
package jiu;
public class StringIndexOutOf {
public static void main(String[] args) {
try{System.out.println("字符串索引越界异常");
String str=args[0];
System.out.println("第四个字符为"+str.charAt(3));
int aa=Integer.parseInt(args[0]);
System.out.println("平方为"+aa*aa);
}catch (Exception e){
System.out.println(e.toString());
}
}
}
编写应用程序,从命令行传入两个整型数作为除数和被除数。要求程序中捕获NumberFormatException 异常。
文件名:Tw
package jiu;
public class Tw {
public static void main(String args[]) {
try{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
System.out.println(a/b);
}catch(NumberFormatException e) {
e.printStackTrace();
}
}
}
自定义异常ExceptionExample,将异常信息传入构造方法。
文件名:ExceptionExample
package jiu;
class ExceptionExample extends Exception{
ExceptionExample(){
super("异常");
}
ExceptionExample(String msg){
super(msg);
}
}