自定义了一个异常,为什么产生异常时,没有输出"你输入非数字的字符了"。
程序通过输入判断输入的是否是数字0-9,如果不是则抛出异常。自定义异常类代码如下:class MyExcep extends NumberFormatException {
public MyExcep() {
System.out.println("你输入非数字的字符了!");
}
}
输入数字代码import java.util.Scanner;class MyExcepTest {
public static int nextNumber()
{
int x = 0;
StringBuffer s = new StringBuffer();
try
{
int c;
while (true)
{
c = new Scanner(System.in).nextInt();
if (c >= 0 && c <= 9) s.append(c);
else
throw new MyExcep();
}
}
catch (Exception e)
{
e.getMessage();
}
finally
{
x = Integer.parseInt(s.toString());
return x;
}
} public static void main(String[] args) {
System.out.println(nextNumber());
}
}
程序通过输入判断输入的是否是数字0-9,如果不是则抛出异常。自定义异常类代码如下:class MyExcep extends NumberFormatException {
public MyExcep() {
System.out.println("你输入非数字的字符了!");
}
}
输入数字代码import java.util.Scanner;class MyExcepTest {
public static int nextNumber()
{
int x = 0;
StringBuffer s = new StringBuffer();
try
{
int c;
while (true)
{
c = new Scanner(System.in).nextInt();
if (c >= 0 && c <= 9) s.append(c);
else
throw new MyExcep();
}
}
catch (Exception e)
{
e.getMessage();
}
finally
{
x = Integer.parseInt(s.toString());
return x;
}
} public static void main(String[] args) {
System.out.println(nextNumber());
}
}
{
int num;
MyException1(int a)
{
num = a;
}
public String toString()
{
return num+"<10! 值必须大于10";
}
}class MyException2 extends Exception
{
int num;
MyException2(int a)
{
num = a;
}
public String toString()
{
return num+">100!/r/n值必须小于100";
}
}class MyExceptionTest
{
static void makeException(int a) throws MyException1,MyException2
{
if(a<10)
throw new MyException1(a);
if(a>100)
throw new MyException2(a);
System.out.println("No Exception");
}
public static void main(String[] args)
{
int a;
try
{
a = Integer.parseInt(args[0]);
makeException(a);
System.out.println("a="+a);
}
catch (MyException1 e)
{
System.out.println(""+e);
}
catch(MyException2 e)
{
System.out.println(""+e);
}
}
}类似上面的,先throw出来再catch
import java.util.Scanner;class MyExcep extends NumberFormatException
{
public MyExcep()
{ } public MyExcep(String s)
{
super(s);
}
}class MyExcepTest
{
public static void nextNumber()
{
int x = 0;
StringBuffer s = new StringBuffer(); int c;
while (true)
{
c = new Scanner(System.in).nextInt();
if (c >= 0 && c <= 9)
{
s.append(c);
x = Integer.parseInt(s.toString()); } else
throw new MyExcep("你输入非数字的字符了!");
System.out.println(x);
} } public static void main(String[] args)
{
nextNumber();
}
}