docx

advertisement
Solution to Practice Problems: Exceptions
1. Tracing Programs
For each program below, show what is displayed on the screen when the code executes.
public class Exceptions-Basic1
{
public static void main(String [] args)
{
System.out.println("start");
String s = null;
System.out.println(s.length());
System.out.println("end");
}
}
screen
start
Exception in thread "main" java.lang.NullPointerException
at Exceptions-Basic1.main(Exceptions-Basic1.java:7)
Java Result: 1
Note: the part that says "Exceptions-Basic1.java:7" tells you the file name
and the line number (in this case, line 7) where the exception occurred.
Line 7 here is the line "System.out.println(s.length());" – the error
happened because we tried to call a method from a String reference variable,
s, that has a null address.
// Assume that the file "input.txt" does NOT exist
import java.util.Scanner;
import java.io.File;
public class Exceptions-Basic2
{
public static void main(String [] args)
{
System.out.println("start");
File f = new File("input.txt");
Scanner sc = new Scanner(f);
System.out.println("end");
}
}
Trick question! Actually, you can't run this program, because it won't
compile. The compiler will tell you:
"unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown".
Note: There are many different kinds of Exceptions, but there are two broad
classes – checked exceptions and unchecked exceptions. Checked exceptions
must be caught or declared to be thrown, or else the program will not
compile. Unchecked exceptions do not need to be caught or declared to be
thrown. FileNotFoundException is an example of a checked exception.
NullPointerException is an example of an unchecked exception. In general,
any exception in the java.io package will be a checked exception.
// Assume that the file "input.txt" does NOT exist
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException
public class Exceptions-ThrowsStatement
{
public static void main(String [] args) throws FileNotFoundException
{
System.out.println("start");
File f = new File("input.txt");
Scanner sc = new Scanner(f);
System.out.println("end");
}
}
screen
start
Exception in thread "main" java.io.FileNotFoundException: input.txt (The
system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:656)
at ExceptionTester.main(Exceptions-ThrowsStatement.java:11)
Java Result: 1
// The Exception class is in the package java.lang,
// which is automatically included in all Java programs.
// So you do not need an import statement for Exception.
public class Exceptions-ThrowYourOwn
{
public static void main(String [] args) throws Exception
{
System.out.println("start");
String s = "this is a message";
// alternative constructor has zero args: Exception e = new Exception();
Exception e = new Exception(s);
throw e;
System.out.println("end");
}
}
Screen
start
Exception in thread "main" java.lang.Exception: this is a message
at Exceptions-ThrowYourOwn.main(Exceptions-ThrowYourOwn.java:12)
Java Result: 1
NOTE1: Technically, this program also will not compile. The compiler will
tell you that the last statement (System.out.println("end");) is an
"unreachable statement". That's because the compiler can figure out that
there is no way this statement will ever execute – the program has to stop
with the "throw e;" statement. To make this program run, you would need to
delete or comment out that last println.
NOTE2: Also, note that the String s that is used to construct the Exception
e is printed out when the Exception is thrown.
public class Exceptions-TryCatch
{
public static void main(String [] args) // Notice NO THROWS STATEMENT!!
{
System.out.println("start");
try {
String s = "this is a message";
Exception e = new Exception(s);
throw e;
}
catch(Exception exc) {
System.out.println(exc.getMessage());
System.out.println(exc.toString());
}
System.out.println("end");
}
}
Screen
start
this is a message
java.lang.Exception: this is a message
end
public class Exceptions-TryCatchExit
{
public static void main(String [] args)
{
System.out.println("start");
try {
String s = "this is a message";
Exception e = new Exception(s);
throw e;
}
catch(Exception exc) {
System.out.println(exc.getMessage());
System.out.println(exc.toString());
System.exit(1); // sometimes I've seen "throw exc;" here instead
}
System.out.println("end");
}
}
Screen
start
this is a message
java.lang.Exception: this is a message
Java Result: 1
public class Exceptions-CatchExceptionType1
{
public static void main(String [] args)
{
System.out.println("start");
try {
throw new Exception("this is a message");
}
catch(NullPointerException npe) {
System.out.println("got a nullpointer exception");
}
catch(FileNotFoundException fnfe) {
System.out.println("got a file not found exception");
}
catch(Exception e) {
System.out.println("got some other exception");
}
System.out.println("end");
}
}
screen
start
got some other exception
end
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException
public class Exceptions-CatchExceptionType2
{
public static void main(String [] args) // notice NO THROWS STATEMENT!!
{
System.out.println("start");
try {
File f = new File("input.txt");
Scanner sc = new Scanner(f);
}
catch(NullPointerException npe) {
System.out.println("got a nullpointer exception");
}
catch(FileNotFoundException fnfe) {
System.out.println("got a file not found exception");
}
catch(Exception e) {
System.out.println("got some other exception");
}
System.out.println("end");
}
}
screen
start
got a file not found exception
end
public class Exceptions-CatchExceptionType3
{
public static void main(String [] args)
{
System.out.println("start");
try {
String s = null;
System.out.println(s.length());
}
catch(NullPointerException npe) {
System.out.println("got a nullpointer exception");
}
catch(FileNotFoundException fnfe) {
System.out.println("got a file not found exception");
}
catch(Exception e) {
System.out.println("got some other exception");
}
System.out.println("end");
}
}
Another trick question! This won't compile either, because the compiler
checks to see if a FileNotFoundException (which is a checked exception) could
possibly be thrown by the try block. In this case, there's nothing there
that could possibly cause a FileNotFoundException, so it won't let you have a
catch block for that exception. Note that in the previous example, the
Scanner could cause a FileNotFoundException, so there it was fine to have a
catch block for it. In the example before that, it looks like it's
impossible to cause a FileNotFoundException, but Java's compiler can't tell
for sure, so it won't complain. If you remove the catch block for the
FileNotFoundException, the program would display:
start
got a nullpointer exception
end
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Exceptions-Finally
{
public static void main(String [] args)
{
System.out.println("start");
Scanner sc = null; // declare and initialize here for wide scope
try {
File f = new File("input.txt");
sc = new Scanner(f);
sc.nextLine();
}
catch(NullPointerException npe) {
System.out.println("got a nullpointer exception");
}
catch(FileNotFoundException fnfe) {
System.out.println("got a file not found exception");
}
catch(Exception e) {
System.out.println("got some other exception");
}
finally {
if(sc!=null) {
sc.close();
}
System.out.println("finally");
}
System.out.println("end");
}
}
screen
start
got a file not found exception
finally
end
NOTE: If the file input.txt WAS there, then the program would display
everything except the line saying "got a file not found exception".
Specifically, it would still display the "finally" line, since the finally {}
block always executes, regardless of whether an exception occurs or not.
Download