Java Programming
Java Programming
Exception Handling –Dealing with errors- benefits of exception handling- the classification of
exceptions –exception hierarchy- checked exceptions and unchecked exceptions- usage of try-
catch-throw-throws and finally-rethrowing exceptions- exception specification- built in
exceptions- creating own exception sub classes.
Multithreading –Differences between multiple processes and multiple threads- thread states-
creating threads- interrupting threads- thread priorities- synchronizing threads- inter –thread
communication- producer consumer pattern
Introduction
o An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instruction.
Or
o An abnormal condition that disrupts Normal program flow.
o There are many cases where abnormal conditions happen during program execution,
such as
o Trying to access an out - of –bounds array elements.
o The file you try to open may not exist.
o The file we want to load may be missing or in the wrong format.
o The other end of your network connection may be non –existence.
o If these cases are not prevented or at least handled properly, either the program will be
aborted abruptly, or the incorrect results or status will be produced.
o When an error occurs with in the java method, the method creates an exception object
and hands it off to the runtime system.
o The exception object contains information about the exception including its type and
the state of the program when the error occurred. The runtime system is then
responsible for finding some code to handle the error.
o In java creating an exception object and handling it to the runtime system is called
throwing an exception.
o Exception is an object that is describes an exceptional ( i.e. error) condition that has
occurred in a piece of code at run time.
o When a exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error. That method may choose to handle
the exception itself, or pass it on. Either way, at some point, the exception is caught and
processed.
o Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code.
o System generated exceptions are automatically thrown by the Java runtime system
Try Block
No
arise or
No Catch Block
Exceptional Handler
appropriate
Catch
block
Finally Block
Optional part
For Example:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of Exc0 to stop,
because once an exception has been thrown, it must be caught by an exception handler and dealt
with immediately. In this example, we haven’t supp the exception is caught by the default handler provided by
the Java run-time system. Any
exception that is not caught by your program will ultimately be processed by the default handler.
The default handler displays a string describing the exception, prints a stack trace from the point
at which the exception occurred, and terminates the program. Here is the output generated when
this example is executed.
java.lang.ArithmeticException: / by
zero at Exc0.main(Exc0.java:4)
Notice how the class name, Exc0; the method name, main; the filename, Exc0.java;
and the line number, 4
Catch block
The catch block is used to process the exception raised. A try block can be one or more
catch blocks can handle a try block.
Catch handles are placed immediately after the try block.
Catch(exceptiontype e)
{
//Error handle routine is placed here for handling exception
}
Program 1
Class trycatch
{
Public static void main(String args[])
{
Int[] no={1,2,3};
Try
{
System.out.println(no[3]);
}
Catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(―Out of bondsǁ);
}
System.out.println(―Quitǁ);
}
}
Output
Program 2 Class
ArithExce
{
Public static void main(String args[])
{
Int a=10;
Int b=0;
Try
{
a=a/b;
System.out.println(―Won’t Printǁ);
}
Catch(ArithmeticException e)
{
System.out.println(―Division by Zero errorǁ); System.out.println(―Change the b valueǁ);
}
System.out.println(―Quitǁ);
}
}
Output
Note:
A try ad its catch statement form a unit.
We cannot use try block alone.
The compiler does not allow any statement between try block and its associated catch
block
Displaying description of an Exception
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
When this version is substituted in the program, and the program is run, each divide-by-
zero error displays the following message:
– Exception: java.lang.ArithmeticException: / by zero
In some cases, more than one exception could be raised by a single piece of code. To handle this
type of situation, you can specify two or more catch clauses, each catching a different type of
exception. When an exception is thrown, each catch statement is inspected in order, and the first
one whose type matches that of the exception is executed. After one catch statement executes,
the others are bypassed, and execution continues after the try/catch block. The following
example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no commandline
parameters, since a will equal zero. It will survive the division if you provide a command-line
argument, setting a to something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program
attempts to assign a value to c[42].
Here is the output generated by running it both
ways: C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by
zero After try/catch blocks.
C:\>java MultiCatch
TestArg a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
Throw Keyword
So far, we have only been catching exceptions that are thrown by the Java Run –Time
systems. How ever, it is possible for our program to throw an exception explicitly, using
the throw statement.
Throw throwableInstance
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable. Simple types, such as int or char, as well as non-Throwable classes, such
as String and Object, cannot be used as exceptions
There are two ways you can obtain a Throwable object:
– using a parameter into a catch clause
– creating one with the new operator.
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of the exception. If it does find a match, control is
transferred to that statement. If not, then the next enclosing try statement is inspected,
and so on. If no matching catch is found, then the default exception handler halts the
program and prints the stack trace
// Demonstrate throw.
class ThrowDemo {
static void demoproc()
{ try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside
demoproc."); throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}}
This program gets two chances to deal with the same error. First, main( ) sets up an
exception context and then calls demoproc( ). The demoproc( ) method then sets up
another exception-handling context and immediately throws a new instance of
NullPointerException, which is caught on the next line. The exception is then rethrown.
Here is the resulting output:
The program also illustrates how to create one of J close attention to this line:
Here, new is used to construct an instance of NullPointerException. All of- Java’ in run-time
exceptions have at least two constructors: one with no parameter and one that
takes a string parameter. When the second form is used, the argument specifies a string
that describes the exception. This string is displayed when the object
is used as an argument to print( ) or println( ). It can also be obtained by a call to
getMessage( ), which is defined by Throwable.
Throws Keyword
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You
do this by including a throws clause in the method’sthrowsclauselistsdeclar the types of exceptions that
a method might throw. This is necessary for all exceptions,
except those of type Error or RuntimeException, or any of their subclasses. All other
exceptions that a method can throw must be declared in the throws clause. If they are
not, a compile-time error will result. This is the general form of a method declaration that
includes a throws clause:
Here, exception-list is a comma-separated list of the exceptions that a method can throw
Program
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{ System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e)
{ System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException
S.No. throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
1) throw an exception. exception.
Checked exception cannot be propagated Checked exception can be propagated with using throw only.
2) throws.
3)
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
4)
You cannot throw multiple You can declare multiple exceptions e.g.
5) exceptions. public void method()throws
IOException,SQLException.
Finally block
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear
path that alters the normal flow through the method. Depending upon how the method is
coded, it is even possible for an exception to cause the method to return prematurely.
This could be a problem in some methods. For example, if a method
opens a file upon entry and closes it upon exit, then you will not want the code that closes
the file to be bypassed by the exception-handling mechanism. The finally keyword is
designed to address this contingency.
finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block. The 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 matches the exception. Any time a method
is about to return to the caller from inside a try/catch block, via an uncaught exception or
an explicit return statement, the finally clause is also executed just before the method
returns. This can be useful for closing file handles and freeing up any other resources that
might have been allocated at the beginning of a method with the intent of disposing of
them before returning. The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try
block. static void procB() {
try {
System.out.println("inside procB");
return;
} finally { System.out.println("procB's
finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC"); }
finally { System.out.println("procC's
finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
In this example, procA( ) prematurely breaks out of the try by throwing an exception. The
finally clause is executed on the way out. procB( )’stry statement is exited via a return
statement. The finally clause is executed before procB( ) returns. In procC( ), the
try statement executes normally, without error. However, the finally block is still
executed. If a finally block is associated with a try, the finally block will be executed
upon conclusion of the try.
procC’sly final
There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below: