Sunteți pe pagina 1din 8

EXCEPTION HANDLING:

Answer the following questions:


Level : easy.
True or false?

1.
Exceptions are sent directly to a caller of the failed method.
2.

Is the following code Correct?


public class BankAccount
{
public void withdraw( double amount)
{
if ( amount> balance )
{
IllegalArgumentException exception
= new IllegalArgumentException(“ Amount exceeds balance”);
}
balance = balance – amount;
}

}

3.
Can exceptions can be overlooked?
4.
Someone withdraws too much money from a bank account. Is the bank account an
IllegalStateException?
5.
To signal an exceptional condition, use a try statement to try an an exception object.
6.
Does a method immediately terminates when you throw an exception?
7.
You place the statement that can cause the exception inside a ?? block and handler inside
a ?? clause .
8.
How should you modify the deposit method to ensure that the balance is never negative?
9.
Suppose you construct a new Bank account with zero balance and then call withdraw(10).
What is the balance afterwards?
10.
Describe checked exceptions and give examples of checked exceptions.
11.
Do the same for unchecked exceptions.
12.
Why are there two kinds of exceptions?
13.
What happens when an exception has no handler?
14.
What is a try block and catch clause?
15.
What is throw early, catch late mean?

16.
What is wrong with this exception handling?

Try
{ FileReader reader= new FileReader(filename);
// Compiler complained about FileNotFoundException.
}
catch ( Exception e) {} // so there!

Equivalent question : Why should you not shut the compiler up by squelching
exceptions?
17.
Should the new exception type such as InsufficientFundException be unchecked or
checked exception? What class should it extend?

18.

What is the difference between throwing an exception and catching an exception?

19.

Why don’t you need to declare that your method might throw a NullPointerException?

20.
What happens if an exception does not have a matching clause?

21.
Is the type of the exception object always the same as the type declared in the catch
clause that matches it?

22.
What is the purpose of the finally clause? Give an example of how it can be used.

23.
Which exception can the next and NextInt methods of the Scanner class throw? Are they
checked exceptions or unchecked exceptions?
24.
How can a program be improved to give a more accurate error report?

MEDIUM AND HARD QUESTIONS:


1.
What are the following exceptions?
✦ IllegalArgumentException:
✦ InputMismatchException:
✦ ArithmeticException:
✦ IOException:
✦ ClassNotFoundException:
2.
Create a program that divide two numbers using a try/catch statement to catch an
exception if thesecond number turns out to be zero:
3.
How can you avoid the ArithmethicException that
results from dividing integer data by zero?
4.
Describe what the following program does in detail:
import java.util.*;
public class GetInteger2
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print(“Enter an integer: “);
int i = GetInteger();
System.out.println(“You entered “ + i);
}
public static int GetInteger()
{
while (!sc.hasNextInt())
{
sc.nextLine();
System.out.print(“That’s not an integer. “
+ “Try again: “);
}
return sc.nextInt();
}
}
5.
Fill in blanks: When you code more than one catch block on a try statement, always list
the more specific exceptions _____. If you include a catch block to catch
Exception, list it _____.

6.
Describe in detail: what is a finally block and show the basic framework for a try
statement with a finally block
7.
Why must the next method be called in the catch block to dispose users invalid input?
What happens if you omit the statement that calls next?

Answers:
1.
FALSE- to the exception handler
2.
yes
3.
false
4.
No. The parameter value is illegal. throw IllegalArgumentException.
5.
False, use a throw to throw an exception object.
6.
yes
7.
Try, catch.
8.
Throw an exception if the amount deposited is less than zero.
9.
The balance is still zero since the last statement of the withdraw method was never
executed.
10.
When you call a method that throws a checked exception , the compiler checks you
don’t ignore it . You must specify what to do with it if it is ever thrown. Examples:
IOException , Exception subclasses.
11.
The compiler does not require you to check exceptions. Example:
IllegalArgumentException , NumberFormatException, NullPointerException , and
all subclasses of RunTimeException .

12.
A checked exception describes a problem that is likely to occur at times ,
no matter how careful you are. An unchecked exception, are your fault.
13.
A error message is printed and program terminates.
Therefore, you should provide exception handlers for all exceptions that your
program might throw.

14.

Each try block contains one or more statements that may cause an exception. Each
catch clause contains the handler for an exception type .

15.
It s better to throw an exception rather than try to come up with an imperfect fix (
returning default value, or doing nothing).

16.

Installing an incompetent handler hides the error condition that could be serious.
Example:

17.

The programmer could of easily prevented the exception condition by checking


whether amount<=account.getBalance() before calling withdraw method. Thus it
is unchecked exception and should extend the RuntimeException class or one of its
subclasses.

18.

You throw an exception to notify some other part of the program that an exceptional
condition has occurred.You catch an exception to handle an exceptional situation
that has occurred elsewhere in the program.
19.
A NullPointerException is an unchecked exception. The programmer is to
be blamed when such an exception occurs because it is the responsibility of the
programmer to test all references for null before using them instead of installing a
handler for that exception.

20.
If an exception has no matching catch clause in the same method, the search for a
matching catch clause continues in the calling method. If the entire program has no
matching catch clause, then the program terminates.

21.
No, the type of the thrown exception may be a subtype of the type of the caught
exception. That commonly happens, for example, when throwing an EOFException
and catching an IOException.

22.

They are all unchecked exceptions. The designers of the Scanner class made this
choice to make the class easy to use for beginning programmers.

23.

The next method can throw:


NoSuchElementException - if no more tokens are available
IllegalStateException - if the scanner is closed
The nextInt method can throw:
InputMismatchException - if the next token does not match the Integer
regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if the scanner is closed
24.
we could print a message indicating that the program expected the file to have
numberOfValues data values (in this case, 0), and that more values than expected
were found.

MEDIUM AND HARD QUESTIONS:


1.

✦ IllegalArgumentException: You passed an incorrect argument to


a method.
✦ InputMismatchException: The console input doesn’t match the
data type expected by a method of the Scanner class.
✦ ArithmeticException: You tried an illegal type of arithmetic operation,
such as dividing an integer by zero.
✦ IOException: A method that performs I/O encountered an unrecoverable
I/O error.
✦ ClassNotFoundException: A necessary class couldn’t be found.
2.
public class DivideByZero
{
public static void main(String[] args)
{
int a = 5;
int b = 0; // you know this won’t work
try
{
int c = a / b; // but you try it anyway
}
catch (ArithmeticException e)
{
System.out.println(“Oops, you can’t divide by
zero.”);
}
}
}
Here, the division occurs within a try block, and a catch block handles
ArithmeticException. ArithmethicException is defined by
java.lang, so an import statement for it isn’t necessary.
3.
you can usually by checking the data before performing
the division:
if (b != 0)
c = a / b;
This eliminates the need for enclosing the division in a try block because
you know the division by zero won’t happen.
4.
The conditional expression in the while statement calls the hasNextInt method of the
Scanner to see if the next value is an integer. The while loop repeats as
long as this call returns false, indicating that the next value is not a valid
integer. The body of the loop calls nextLine to discard the bad data and
displays an error message. The loop ends only when you know you have
good data in the input stream, so the return statement calls nextInt to
parse the data to an integer and return the resulting value.
5.
FIRST,LAST.
6.
A finally block is a block that appears after all of the catch blocks for a
statement. It’s executed whether or not any exceptions are thrown by the
try block or caught by any catch blocks. Its purpose is to let you clean up
any mess that might be left behind by the exception, such as open files or
database connections.
The basic framework for a try statement with a finally block is this:
try
{
statements that can throw exceptions
}
catch (exception-type identifier)
{
statements executed when exception is thrown
}
finally
{
statements that are executed whether or not
exceptions occur
}

7.

The next method must be called in the catch block to dispose of the
user’s invalid input because the nextInt method leaves the input value
in the Scanner’s input stream if an InputMismatchException is
thrown. If you omit the statement that calls next, the while loop keeps
reading it, throws an exception, and displays an error message in an infinite
loop.

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