public class H2{
static void check(String str1) //throws NumberFormatException //这个地方为什么有和没有是一样的?
{
char ch;
for(int i=0;i<str1.length();i++)
{
ch=str1.charAt(i);// arAt(int index)返回指定索引处的 char 值
if(!Character.isDigit(ch))//public static boolean isDigit(int codePoint)
throw new NumberFormatException();
}
}
public static void main(String args[])
{
int num;
try
{
check(args[0]);
num=Integer.parseInt(args[0]);
if(num>60)
System.out.println("成绩为:"+num+"及格");
else
System.out.println("成绩为:"+num+"不及格");
}
catch (NumberFormatException e)
{
System.out.println("输入的参数不是数值类型");
}
catch(Exception e)
{
System.out.println("命令行中没有提供参数");
}
}
}
static void check(String str1) //throws NumberFormatException //这个地方为什么有和没有是一样的?
{
char ch;
for(int i=0;i<str1.length();i++)
{
ch=str1.charAt(i);// arAt(int index)返回指定索引处的 char 值
if(!Character.isDigit(ch))//public static boolean isDigit(int codePoint)
throw new NumberFormatException();
}
}
public static void main(String args[])
{
int num;
try
{
check(args[0]);
num=Integer.parseInt(args[0]);
if(num>60)
System.out.println("成绩为:"+num+"及格");
else
System.out.println("成绩为:"+num+"不及格");
}
catch (NumberFormatException e)
{
System.out.println("输入的参数不是数值类型");
}
catch(Exception e)
{
System.out.println("命令行中没有提供参数");
}
}
}
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IllegalArgumentException
java.lang.NumberFormatException从上面的这个类的继承结构可以看出NumberFormatException是一个RuntimeException,而RuntimeException是没有必要显式声明的,也就是可以不要throws NumberFormatException,详细可以看看jdk的文档如下:RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.
static void fun(){
if(true){
throw new Exception("asdf");
}
}
public static void main(String[] args){
try{
fun();
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}我这样就报异常