public class ExceptionDemo1
{
public static void main(String[] args)
{
String firstName = null;
try
{
// It will throw NullPointerException
System.out.println(firstName.length());
}
catch (NullPointerException nullPointerException)
{
System.out.println("String value is null.");
}
catch (Exception exception)
{
exception.printStackTrace();
}
String lastName = "Peter";
String fullName = firstName + lastName;
System.out.println("fullName = " + fullName);
}
}
Output String value is null.
fullName = nullPeter
ExceptionDemo2.java public class ExceptionDemo2
{
public static void main(String[] args)
{
String firstName = null;
try
{
// It will throw NullPointerException
System.out.println(firstName.length());
}
catch (Exception exception)
{
exception.printStackTrace();
}
String lastName = "Peter";
String fullName = firstName + lastName;
System.out.println("fullName = " + fullName);
}
}
Output java.lang.NullPointerException
at ExceptionDemo2.main(ExceptionDemo2.java:10)
fullName = nullPeter
ExceptionDemo3.java public class ExceptionDemo3
{
public static void main(String[] args)
{
String firstName = null;
try
{
// It will throw NullPointerException
System.out.println(firstName.length());
}
catch (Exception exception)
{
exception.printStackTrace();
}
catch (NullPointerException nullPointerException)
{
System.out.println("String value is null.");
}
String lastName = "Peter";
String fullName = firstName + lastName;
System.out.println("fullName = " + fullName);
}
}
Output Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable catch block for NullPointerException. It is already handled by the catch block for Exception
at ExceptionDemo3.main(ExceptionDemo3.java:19)