Sunteți pe pagina 1din 5

Java Exception Handling

1) What is the difference between ‘throw’ and ‘throws’ ?And it’s application?

Ans : Exceptions that are thrown by java runtime systems can be handled by Try and
catch blocks. With throw exception we can handle the exceptions thrown by the
program itself. If a method is capable of causing an exception that it does not

handle, it must specify this behavior so the callers of the method can guard

against that exception.

2) What is the difference between ‘Exception’ and ‘error’ in java?

Ans : Exception and Error are the subclasses of the Throwable class. Exception class is
used for exceptional conditions that user program should catch. With exception class
we can subclass to create our own custom exception.

Error defines exceptions that are not excepted to be caught by you


program. Example is Stack Overflow.
3) What is ‘Resource leak’?

Ans : Freeing up other resources that might have been allocated at the beginning of a
method.

4)What is the ‘finally’ block?

Ans : Finally block will execute whether or not an exception is thrown. If an exception is
thrown, the finally block will execute even if no catch statement match the exception.
Any time a method is about to return to the caller from inside try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also execute.

5) Can we have catch block with out try block? If so when?

Ans : No. Try/Catch or Try/finally form a unit.

6) What is the difference between the following statements?

Catch (Exception e),

Catch (Error err),

Catch (Throwable t)

Ans :
7) What will happen to the Exception object after exception handling?

Ans : It will go for Garbage Collector. And frees the memory.

8) How many Exceptions we can define in ‘throws’ clause?

Ans : We can define multiple exceptions in throws clause.

Signature is..

type method-name (parameter-list) throws exception-list

9) The finally block is executed when an exception is thrown, even if no catch matches
it.

True/False

Ans : True

10) The subclass exception should precede the base class exception when used within
the catch clause.

True/False

Ans : True

11) Exceptions can be caught or rethrown to a calling method.

True/False

Ans : True

12) The statements following the throw keyword in a program are not executed.

True/False

Ans : True

13) The toString ( ) method in the user-defined exception class is overridden.

True/False

Ans : True

I. Introduction

An exception is an error thrown by a class or method reporting an error in operation. For example,
dividing by zero is undefined in mathematics, and a calculation can fail if this winds up being the case
because of an error in user input. In this particular case an ArithmeticException is thrown, and unless
the programmer looks for this exception and manually puts in code to handle it, the program will crash
stating the exception thrown and a stack trace, which would be unhelpful to a casual user of a Java
program. If the programmer handles the exception, he could deliver a useful error to the user and
return the user to the beginning of the program so that they could continue to use it.

II. Common Exceptions

There are many different exceptions that can be thrown by a program, and the Java API contains quite
a few. A lot are contained in the default package, java.lang; however, when you start using more
functionality such as AWT, Swing, or java.io, the packages may also contain additional exceptions
thrown by those libraries. As you start expanding the functionality, it might be a good idea to look at
potential exceptions in the package and when they might be thrown in the course of your application.
Here is a primer of some:

• ArithmeticException--thrown if a program attempts to perform division by zero


• ArrayIndexOutOfBoundsException--thrown if a program attempts to access an index of an array that
does not exist
• StringIndexOutOfBoundsException--thrown if a program attempts to access a character at a non-
existent index in a String
• NullPointerException--thrown if the JVM attempts to perform an operation on an Object that points
to no data, or null
• NumberFormatException--thrown if a program is attempting to convert a string to a numerical
datatype, and the string contains inappropriate characters (i.e. 'z' or 'Q')
• ClassNotFoundException--thrown if a program can not find a class it depends at runtime (i.e., the
class's ".class" file cannot be found or was removed from the CLASSPATH)
• IOException--actually contained in java.io, but it is thrown if the JVM failed to open an I/O stream

As I said before, many different exceptions exist, and you should probably use your API
documentation to learn about additional exceptions that may apply to your particular application.

III. "Catching" Exceptions

The java language contains keywords used specifically for testing for and handling exceptions. The
ones we will be using here are try and catch, and they must be used in conjunction with one another.
They sort of work like if-else:

try{
/*
Contains code to be tested
*/
}catch(Exception e){
/*
Contains code to be executed if instanced of Exception is caught
*/
}

The catch statement can look for all exceptions, using the Exception superclass, or it can catch a
specific exception that you think could be thrown in the code you are testing with the try block. You
can even have multiple catch blocks to catch and execute custom code for a number of different
errors. A good thing to note would be that any particular exception that is caught is compared with
each catch statement sequentially; so it is a good idea to put more generic exceptions, like Exception,
towards the bottom of the list.

IV. The Throwable Superclass

The catch statement also stores an instance of the exception that was caught in the variable that the
programmer uses, in the previous example Exception e. While all exceptions are subclasses of
Exception, Exception itself is a subclass of Throwable, which contains a nice suite of methods that you
can use to get all kinds of information to report about your exceptions:

• getMessage()--returns the error message reported by the exception in a String


• printStackTrace()--prints the stack trace of the exception to standard output, useful for debugging
purposes in locating where the exception occurred
• printStackTrace(PrintStream s)--prints the stack trace to an alternative output stream
• printStackTrace(PrintWriter s)--prints the stack trace to a file, this way you can log stack traces
transparent to the user or log for later reference
• toString()--if you just decide to print out the exception it will print out this: NAME_OF_EXCEPTION:
getMessage().

Using the catch you now have control over what the error message is and where it goes.

V. Effectively using try-catch

In this section, I'm going to give you a few code samples on using try-catch blocks to give you an idea
of the flexibility you as a programmer have over exceptions in your programs. The scenario is a user
has input a file name to a program of a file that does not exist. In this scenario we are going to be
using a text-based program; however, in a graphical environment you can easily use the catch block to
draw dialog boxes. In the first example, we want to print a useful error message and exit the program
gracefully, saving the user from the confusing stack trace with something useful:

try{
BufferedReader in = new BufferedReader(new FileReader(userInput));
System.out.println(in.readLine())
}catch(IOException e){
System.err.println(e.getMessage());
System.err.println("Error: " + userInput + " is not a valid file. Please verify that the
file exists and that you have access to it.");
System.exit(1);
}

Here, System.err.println() prints the error message to standard error output which is a high priority
buffer that is used to report error messages to the console. If you're being a good programmer, you
have separate methods that handle the different functionality of your programs; this way you can
easily start the program from a previous place in the program before an exception occurs. In this next
example, the user inputs the filename through the function getUserInput() elsewhere in the program;
we want to report the "helpful error message" to the user and return the user to a place where he can
enter a new filename.

public String getFileInput(String userInput){


try{
BufferedReader in = new BufferedReader(new FileReader(userInput));
return in.readLine();
}catch(IOException e){
System.err.println(e.getMessage());
System.err.println("Error: " + userInput + " is not a valid file. Please verify that the
file exists and that you have access to it.");
return getFileInput(getUserInput());
}

S-ar putea să vă placă și