在Exception e 中,getMessage()方法和toString()方法的区别

第一个是使用getMesage()方法
import java.util.Scanner;

class myException extends Exception
{
public myException()
{
super(“The price is low”);
}

}
public class TestDemo8
{
public static void main(String args[])
{
try {
Scanner scan = new Scanner(System.in);
float price = scan.nextFloat();
if(price < 10)
{
throw new myException();
}
else
{
System.out.println("The price is " + price);
}

    }catch (Exception e)
    {
        System.out.println(e.getMessage());
    }
}

}
比如说输入的价格为9
打印结果如下:
9
The price is low
Process finished with exit code 0

第二个是使用toString()方法
import java.util.Scanner;

class myException extends Exception
{
public myException()
{
super(“The price is low”);
}

}
public class TestDemo8
{
public static void main(String args[])
{
try {
Scanner scan = new Scanner(System.in);
float price = scan.nextFloat();
if(price < 10)
{
throw new myException();
}
else
{
System.out.println("The price is " + price);
}

    }catch (Exception e)
    {
        System.out.println(e.toString());
    }
}

}
比如说:输入的价格是9
打印结果如下:
9
myException: The price is low
Process finished with exit code 0

比较以上两点,我们可以看出在使用toString()方法时,与getMessage()相比较控制台会多输出一个myException,所以我们可以总计一下:
getMessage() : 只是获取了异常的详细信息字符串
toString() :不仅获取了异常的详细信息而且还会输出产生异常信息的类的名称。

你可能感兴趣的:(java相关知识点)