Java Exception

An Example
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
// Display the result
System.out.println("The number entered is " + number);
}
}


Types of Error
Syntax Error
– Rules of the languages are violated
– Detected by the compiler
Runtime Error
– Execution time, an operation may be impossible
to carry out
Logical Errors
– Program does not perform the way it is intended
to be
 

Example Revisited
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();  //Runtime error
// Display the result
System.out.println("The number entered is " + number);
}

• An exception is any unusual event, either
erroneous or not, detectable by either
hardware or software, that may require
special processing
• The special processing that may be required
after detection of an exception is called
exception handling
• The exception handling code unit is called an
exception handler 

Exception Handling
• Based on that of C++, but more in line with
OOP philosophy
• All exceptions are objects of classes that are
descendants of the Throwable class 
• The Java library includes two subclasses of Throwable :
Error
• Internal system errors
• Thrown by the Java interpreter for events such as heap overflow
• Never handled by user programs
– Exception
• User-defined exceptions are usually subclasses of this
• Has two predefined subclasses, IOException and

RuntimeException
– RuntimeException
• Caused by programming errors
• Bad Typecast, ArrayIndexOutOfBoundsException
and NullPointerException 

Unchecked Exceptions
• Logical errors
• Not recoverable
– Should be corrected in the codes
• Hence, not very important to handle
• Java does not force to handle these
exceptions
• RuntimeException, Error 

Checked Exceptions
• All, other than unchecked exceptions
• Should be handled properly
• Java compiler forces the programmer to check
and deal with the exceptions 

method1() {try {
invoke command1;
}
catch (Exception ex) {
Process exception;
}
}
method2() throws Exception {if (an error occurs) {
throw new Exception();
}

Declaring Exceptions
• A method must state the types of checked
exceptions it might throw
public void myMethod()
throws IOException
Or
public void myMethod()
throws IOException, OtherException 

Throwing Exception
• When the program detects an error, the
program can create an instance of an
appropriate exception type and throw it.
throw new TheException();
TheException ex = new TheException();
throw ex; 

Example
public void setRadius(double newRadius)
throws IllegalArgumentException
{
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");


Throwing Exception
• A method can throw different exceptions
• These should be written comma separated
void method1()
throws Exception1, Exception2, … {
Statement1;

}

Handling Exceptions
• Java forces to deal with Checked Exceptions
• Any code that may incur a Checked exception
SHOULD be kept inside a TRY block
OR
• The method Should declare to throw the
exception to the calling method 

void p1() {
try {
statements; // Statements that may
throw exceptions

}
catch (Exception1 exVar1) {
handler for exception1;
}

void p1() throws Exception1{
statements; // Statements that may
throw exceptions

}

• A “try” block can catch different
exceptions.
• Start with the most specific exceptions
FileNotFoundException is a subclass of
IOException
– It MUST appear before IOException in the
catch list
 

Example
public void method1()
{
FileInputStream aFile;
try
{
aFile = new FileInputStream(...);
int aChar = aFile.read();
//...
}
catch(FileNotFoundException x)
{
// ...
}
catch(IOException x)
{
// ... 

Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;

• For normal execution:
– try block executes, then finally block executes, then other statements
execute
• When an error is caught and the catch block throws an
exception or returns:
– try block is interrupted
– catch block executes (until throw or return statement)
– finally block executes
• When error is caught and catch block doesn’t throw an
exception or return:
– try block is interrupted
– catch block executes
– finally block executes
– other statements execute
• When an error occurs that is not caught:
– try block is interrupted
– finally block executes 

try
{ p.a = 10; }
catch (NullPointerException e)
{ System.out.println("p was null"); }
catch (Exception e)
{ System.out.println("other error occurred"); }
catch (Object obj)
{ System.out.println("Who threw that object?"); }
finally
{ System.out.println(“final processing"); }
System.out.println(“Continue with more
statements"); 

Catching Exception
• When an exception occurs, the nested try/catch statements
are searched for a catch parameter matching the exception
class
• A parameter is said to match the exception if it:
– is the same class as the exception; or
– is a superclass of the exception; or
– if the parameter is an interface, the exception class implements the
interface.
• The first try/catch statement that has a parameter that
matches the exception has its catch statement executed.
• After the catch statement executes, execution resumes with
the finally statement, then the statements after the try/catch
statement.

print("now");
try
{ print("is ");
throw new MyException();
print("a ");
}
catch(MyException e)
{ print("the "); }
print("time\n");

• Prints "now is the time".

The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}


• This clause is always executed
– Be it a Success or a Failure

try {
statement1;
statement2;

}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

try {
statement1;
statement2;->Exception

}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Cautions
• Exception handling usually requires more time
and resources
• It requires
– instantiating a new exception object,
– rolling back the call stack, and
– propagating the errors to the calling methods

When not to Use Exceptions
• Do not use to deal with simple scenarios
where you can handle it with less complex
codes
• Example:
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}

• The block can be simply replaced by a simpler
code
• Example:
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");

Throwable
Throwable class
  – Method printStackTrace
        • Prints method call stack
  – Method getStackTrace
        • Obtains stack-trace information
  – Method getMessage
       • Returns descriptive string

Example
System.err.println( exception.getMessage());
exception.printStackTrace();
StackTraceElement[] traceElements = exception.getStackTrace();
for ( int i = 0; i < traceElements.length; i++ ) {
StackTraceElement currentElement = traceElements[ i ];
System.out.print( currentElement.getClassName() + "\t" );
System.out.print( currentElement.getFileName() + "\t" );
}

Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics