• No results found

Catching an Exception

In document Java 8 Programming Black Book (Page 170-174)

System.out.println();

System.out.println(str);

System.out.println(sb.toString()); } }

In the preceding code, we have used a special class called the Scanner class; let’s give you a brief introduction of it.

You can read input from either the keyboard or a text file by using Scanner class. This class provides a simple and standard mechanism for reading input; the complete Scanner class can be accessed by importing java.util.Scanner. The input received by the Scanner class is broken into tokens. For breaking, Scanner uses delimiter pattern, which by default matches whitespace. These tokens are further converted into values of various types by using the following methods.

The following code allows a user to read a number from System.in:

Scanner scan = new Scanner(System.in);

int i = scan.nextInt();

When the program is compiled and run, it involves an interactive session. So, on entering any string, you’ll get the symbol ‘*’, at the (‘a’,‘e’,‘i’,‘o’,‘u’) vowel’s position. The output is shown here:

C:\>java App pretty hard for Java to know what to do when you do that. Why not catch ArithmeticException exceptions and handle divisions by zero yourself?” The NP says, “Tell me more!”

You can use try/catch blocks to handle runtime errors, called exceptions. Exceptions are encapsulated into objects that extend the Throwable class. In fact, there’s another kind of runtime error in Java that’s built on the Throwable class—it’s called Error. However, this type of error is serious and cannot be caught in code. Here’s the inheritance diagram for the Throwable class:

java.lang.Object

|____java.lang.Throwable

You’ll find the constructors of the Throwable class in Table 4.2 and its methods in Table 4.3. Note, in particular, the getMessage() method, which returns an error message you can display to the user, and the toString() method, which lets you print out an exception object as part of a string, like this:

System.out.println("Exception: " + e)

Immediate Solutions

Here, e is an exception object.

Table 4.2: Constructors of the Throwable class

Constructor Does this

Throwable() It constructs a new Throwable object

Throwable(String message) It constructs a new Throwable object with the indicated error message

Throwable(String message , Throwable cause)

It constructs a new Throwable object with the specified detail message and cause

Throwable(Throwable cause) It constructs a new Throwable object with the specified cause and detail messageof(cause==null ?null:cause.toString()) (which typically contains the class and detail message of cause) protected Throwable (String message,

Throwable cause, boolean enableSuppression, boolean writableStackTrace)

It constructs a new Throwable object with the indicated error message, cause, suppression disabled, or enabled, and writable stack trace disabled or enabled

Table 4.3: Methods of the Throwable class

Method Does this

void addSuppressed(Throwable exception)

It appends the indicated exception to the exceptions that were suppressed to deliver this exception

Throwable fillInStackTrace() It fills in the execution stack trace

Throwable getCause() It yields the cause of this Throwable object or null in case the cause doesn’t exist or not known

String getLocalizedMessage() It gets a localized description of this Throwable object String getMessage() It gets the error message string of this Throwable object

StackTraceElement[] getStackTrace() It provides programmatic access to the stack trace information printed by printStackTrace()

Throwable[] getSuppressed() It returns an array containing all the exceptions suppressed to deliver this exception

Throwable initCause (Throwable cause)

It initializes the cause of this throwable to the specified value

void printStackTrace() It prints the stack trace to the standard error stream void printStackTrace

(PrintStream s)

It prints the stack trace to the indicated print stream

void printStackTrace (PrintWriter s)

It prints the stack trace to the indicated print writer

void setStackTrace

(StackTraceElement [] stackTrace)

It sets the stack trace elements that will be returned by getStackTrace() and printed by printStackTrace() and related methods

String toString() It gets a short description of this Throwable object Here’s the inheritance diagram for the Exception class:

java.lang.Object

|____java.lang.Throwable |____java.lang.Exception

You’ll find the constructors of the Exception class in Table 4.4. Here’s how you use a try/catch block in general:

try { } // Sensitive code

catch (Exception1Type e1) { } // Handle exception1 type catch (Exception2Type e1) { } // Handle exception2 type . . .

finally { } // Code to be executed after try-catch block ends

Table 4.4: Constructors of the Exception class

Constructor Does this

Exception() It constructs an Exception object with null as its detail message Exception(String s) It constructs an Exception object with the indicated detail

message message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled

Exception

(Throwable cause)

It constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause)

When some sensitive code inside a try block throws an exception, you can catch it with a catch block. You can also use a finally block to execute code after the try/ catch block is complete, and the code in the finally block will be executed whether or not an exception occurred. You can use a finally block to handle exceptions not explicitly caught in a catch block. There are many, many different types of exceptions in Java, and you’ll find some of the exception classes in Table 4.5.

Table 4.5: Some Java exception classes

AclNotFoundException ActivationException AlreadyBoundException

ApplicationException AWTException BackingStoreException

BadLocationException CertificateException ClassNotFoundException CloneNotSupportedException DataFormatException DestroyFailedException ExpandVetoException FontFormatException GeneralSecurityException

GSSException IllegalAccessException InstantiationException

InterruptedException IntrospectionException InvalidMidiDataException InvalidPreferencesFormatExcepti

on

InvocationTargetException IOException

LastOwnerException LineUnavailableException MidiUnavailableException MimeTypeParseException NamingException NoninvertibleTransformExcep

tion

NoSuchFieldException NoSuchMethodException NotBoundException

NotOwnerException ParseException ParserConfigurationExcepti

on

PrinterException PrintException PrivilegedActionException

PropertyVetoException RefreshFailedException RemarshalException

RuntimeException SAXException ServerNotActiveException

SQLException TooManyListenersException TransformerException UnsupportedAudioFileException UnsupportedCallbackExcepti

on

UnsupportedFlavorException

UnsupportedLookAndFeelException URISyntaxException UserException XAException

Take a look at this simple example that divides two numbers and uses try/catch statement to catch an exception, if the second number turns out to be zero:

public class Divide {

public static void main(String[] args) { int d = 5;

int z = 0;

Immediate Solutions try { int quotient = d/z; }

catch (ArithmeticException e) { System.out.println ("Oops!!"); } }

}

Here’s the output of the preceding code:

C:\> java Divide Oops!!

Another example that uses a method to get a valid integer from the user is as follows:

import java.util.*;

public class VerifyInt {

static Scanner scan = new Scanner(System.in);

public static void main(String[] args) { System.out.print("Enter an integer: ");

int x = VerifyInt();

System.out.println("You have entered " + x); } public static int VerifyInt() {

while (true) {

try { return scan.nextInt(); }

catch (InputMismatchException e) {

scan.next();

System.out.print("It is not an integer. "

+ "Try again: "); } }

It is not an integer. Try again: 14.0 It is not an integer. Try again: 7.6 package, including the MismatchException class. When an InputMismatchException is thrown, the nextInt() method leaves the input value in the Scanner’s input stream. Then the scan.next() method in the catch block disposes of the user’s invalid input. If this method (scan.next()) is omitted, the while loop keeps reading the input stream, throws an exception, and displays an error message in an infinite loop.

Here’s one example of catching an exception. In this case, we’re catching an “array index out of bounds”

exception:

public class Excep {

public static void main(String args[]) {

try {

int array[] = new int[100];

array[100] = 100; }

catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Exception: " + e.getMessage());

e.printStackTrace(); }

} }

When you run this example, here’s the result you get, which includes an error message and a stack trace that indicates where the exception occurred:

C:\>java Excep Exception: 100

java.lang.ArrayIndexOutOfBoundsException: 100 at Excep.main(Excep.java:5)

You can also pass exceptions back to methods that called the current method with the throws keyword. Here’s an example in which we indicate that the doSomeWork() method can throw an exception of class ArithmeticException, which will be caught in the calling method (or, if not, by the default exception handler

in Java), by specifying the throws keyword in the method’s definition (note that if you use the throws keyword like this, you don’t need a try/catch block in the method’s body):

public class Excep2 {

public static void main(String args[]) { try { doSomeWork(); }

catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Exception: " + e.getMessage());

e.printStackTrace(); } }

static void doSomeWork() throws ArithmeticException { int array[] = new int[100]; at Excep2.doSomeWork(Excep2.java:9) at Excep2.main(Excep2.java:3)

Here is another example by using the FileNotFoundException. A string is passed to the constructor that contains the path and name of a file that exists on your computer. In case the file is not found, a FileNotFoundException is thrown. You’ll get acquainted with file operations later:

import java.io.*;

public class FileExcep {

public static void main(String[] args) { openFile("test.bmp"); } public static void openFile(String name) {

FileInputStream f = new FileInputStream(name); } }

You’ll notice that you cannot compile this example successfully, as the compiler displays the following error:

C:\> javac FileExcep.java

FileExcep.java:5: error: unreported exception FileNotFoundException; must be caught or declared to be thrown

FileInputStream f = new FileInputStream(name); } ^

1 error

This message means that you need to take care of the FileNotFoundException. To do so, you need to catch this exception by using the try statement:

import java.io.*;

public class FileExcep {

public static void main(String[] args) { openFile("test1.bmp"); } public static void openFile(String name) {

try { FileInputStream f = new FileInputStream(name); } catch (FileNotFoundException e) {

System.out.println("File not found."); } }

}

On executing this example, the following result gets displayed:

C:\>java FileExcep File not found.

In document Java 8 Programming Black Book (Page 170-174)

Related documents