public class BadString
{
public static void main(String[] args)
{
System.out.println("Hello World!");
String name=null;
try
{
if(name.equals("exception"))
System.out.println("My name is "+name);
}
catch (ArithmeticException e)
{
System.out.println("catch an Arithmetic Exception!");
}
catch (NullPointerException e)
{
System.out.println("catch a Null Porinter Exception !");
}
}
}

public class catchNullString
{
public static void main(String[] args)
{
System.out.println("Hello World!");
String name=null;
try
{
if(name.equals("exception"))
System.out.println("My name is "+name);
}
catch (Exception e)
{
System.out.println("catch an Exception!");
}
catch (NullPointerException e)
{
System.out.println("catch a Null Porinter Exception !");
}
}
}

public class catchNullString
{
public static void main(String[] args)
{
System.out.println("Hello World!");
String name=null;
try
{
if(name.equals("exception"))
System.out.println("My name is "+name);
}
catch (NullPointerException e)
{
System.out.println("catch an Null Pointer Exception!");
}
catch (Exception e)
{
System.out.println("catch a Exception !");
}
}
}

Exception是NullPointerException的父类....
catch子句中例外参数的声明原则是从特殊到一般,即先声明可捕获的子类类型,再声明可以捕获的父类类型...
本文通过三个示例演示了如何在Java中正确地处理NullPointerException和Exception。强调了catch子句中异常参数的声明应遵循从具体到抽象的原则,即先声明特定异常类型再声明其父类型。
163

被折叠的 条评论
为什么被折叠?



