Core Java - delhip

errorhandleSoftware and s/w Development

Nov 18, 2013 (3 years and 8 months ago)

79 views

Core Java


Chapter 1.The Need of JAVA


Chapter 2.JAVA Overview


Chapter 3.Data Types, Constants, Variables


Chapter 4.Operators


Chapter 5.Control Statements


Chapter 6.Classes


Chapter 7.Methods


Chapter 8.Inheritance


Chapter 9.Arrays,Strings& Vectors


Chapter 10.Interface


Chapter 11.Packages


Chapter 12.Multithreading


Chapter 13.Exception Handling


Chapter 14.Applets

Exception Handling:


A Java
Exception

is an object that describes an exceptional
condition that has occurred in our code. When an exceptional
condition arises, an object representing that exception is created
and thrown in the method that caused the error. That exception
is caught and handled.


Exceptions can be generated by the
java run time system
, or
they can be
manually generated
by our code. Exceptions thrown
by java relate to fundamental errors that violate the rules of Java
language or Java execution environment. Manual exceptions
report some error condition to the caller of method.


The process of catching the exception object thrown by some
error condition and reports us to take corrective actions is called
Exception Handling.

Java exception handling is managed via five keywords:
try, catch,
throw, throws & finally.


Program statements that you want to monitor for exceptions
are contained within a
try
block.


If an exception occurs within the
try block
, it is
thrown.
Our

code

can catch this
exception using
catch
and handle it in some
rational manner.


System
-
generated exceptions are
automatically thrown by the
Java run
-
time system.


To manually throw an exception, use the keyword
throw.


In some cases, an exception that is thrown out of a method
must be specified

as such by a
throws
clause
.
Any code that
absolutely must be executed upon exiting from a try block is put
in a
finally

block.



Exception Types


All Exceptions are sub classes of built
-
in class
Throwable
. This
has two more sub classes
Exception and Error.



Exception class:
This class is used for exceptional conditions
that user program should catch. This is also the class that we can
sub class to create our own custom exceptions. This Exception
class has one more important sub class called
Runtime
Exception
. These Runtime Exceptions are automatically defined.


Error class:

These exceptions are not caught under normal
conditions. Exceptions of type
Error

are related to errors that
occur in the
Java virtual machine

itself
,
and not in your program.
These types of exceptions are beyond your control, and your
program will not usually deal with them.


Exception Hierarchy

class A{ // try & catch blocks

int a,b;

void divide() {


try{

System.out.println("exc is"+(a/b));

}

catch(Exception e){

System.out.println(e);}

} } // A

class exc{

public static void main(String args[]){


A a1=new A(); a1.a=0;a1.b=0; a1.divide();}};



class ExcDemo1

{

public static void main(String args[])


{

int nums[] = new int[4];

try {

System.out.println("Before exception is generated.");

// Generate an index out
-
of
-
bounds exception.

nums[7] = 10;

System.out.println("this won't be displayed");

}



catch (ArrayIndexOutOfBoundsException exc) {

// catch the exception

System.out.println("Index out
-
of
-
bounds!");

}

System.out.println("After catch statement.");

}

}

O/P:

Before exception is generated.

Index out
-
of
-
bounds!

After catch statement.


finally:

This finally block must executes and it is
regardless of whether the exception is thrown or
not.

This finally block is used in the cases where to
relieve from the resources such as closing the
files and closing the connections etc…prefer to
write the code that must be executed and the
operations that must be performed..

finally{

…. }

class A{ //finally block

int a,b,c,d;

void divide() {


try{

System.out.println("exc is"+(a/b));

}

catch(Exception e){

System.out.println(e);

}

finally{

System.out.println(“division is"+(c/d));

}

} // divide()

} // A




class exc{

public static void main(String args[]){


A a1=new A();

a1.a=0;a1.b=0;

a1.c=20; a1.d=10;


a1.divide();

}

}



throw

The program can also throw the exception explicitly
using throw statement.

throw new Throwable
-
sub class;

The flow of execution stops immediately after throw
statement,any subsequesnt statements are not
executed. The nearest try block is inspected to see it it
has a matching catch statement. If no catch is found ,
then the default handler halts the program and prints
the stack trace.


//rethrow an exception using throw

class Throws{

static void throwone(){

try{

throw new IllegalAccessException(“exc”);


}

catch(IllegalAccessException e)

{

System.out.println(“caught inside throwdemo”);

throw

e; // rethrow the exception

} //catch

} // throwone()


public static void main(String args[])

{

try{


throwone();

}

catch(IllegalAccessException e)

{

System.out.println(e);

}}}


throws

In some cases, if a method generates an exception that it
doesnot

handle, it must declare that exception in a
throws
clause. Here is the general form of a method that includes a
throws clause.

ret
-
type
methName
(
param
-
list) throws except
-
list {

// body

}

Here,
except
-
list is a comma
-
separated list of exceptions that the
method might throw outside
of itself.

subclasses of
Error or
RuntimeException

don’t need to be
specified in a throws list
.
Java simply assumes that a method
may throw one. All other types of exceptions
do need to be

declared. Failure to do so causes a compile
-
time error.



class A{ //throws block

int a,b;

void divide() throws Exception{


System.out.println(a/b);

} //divide} // A

class exc{

public static void main(String args[]){


A a1=new A(); a1.a=0;a1.b=0;

try{

a1.divide();}

catch(Exception e){

System.out.println(e);}

}};


class Throws{

static void throwone()

{

System.out.println(“ inside throwone”);

throw new IllegalAccessException(“exc”);

}

Public static void main(String args[]){

try{ throwone();}

catch(IllegalAccessException e){

System.out.println(“e);

}}}



Multiple Catch statements

We can associate more than one catch statement with a

try.
In
fact, it is

common to do so. However, each
catch
must catch a
different type of exception.

There is one important point about multiple
catch
statements
that relates to subclasses. A
catch
clause for a
superclass

will also
match any of its subclasses. For example, since the
superclass

of
all exceptions is
Throwable
,
to catch all possible exceptions,
catch

Throwable
.

class ExcDemo5 {

public static void main(String args[]) {

// Here,
numer

is longer than denom.

int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 };

int denom[] = { 2, 0, 4, 4, 0, 8 };



for(
int

i
=0;
i
<
numer.length
;
i
++) {

try {

System.out.println
(
numer
[
i
] + " / " +

denom
[
i
] + " is " +

numer
[
i
]/
denom
[
i
]);

}

catch (
ArrayIndexOutOfBoundsException

exc
) {

// catch the exception

System.out.println
("No matching element found.");

}

catch (
Throwable

exc
) {

System.out.println
("Some exception occurred.");

}}}}



Nested

try block :

One try block can be nested within another.
An exception generated within the inner try block

that is not caught by a catch associated with that try is
propagated to the outer try block. For example, here the
ArrayIndexOutOfBoundsException

is not caught by the inner
catch, but
by the outer
catch.


class
NestTrys

{

public static void main(String args[]) {

// Here,
numer

is longer than denom.

int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 };

int denom[] = { 2, 0, 4, 4, 0, 8 };

try { // outer try

for(int i=0; i<numer.length; i++) {

try { // nested try

System.out.println(numer[i] + " / " +

denom[i] + " is " +

numer[i]/denom[i]);

}

catch (ArithmeticException exc) {

// catch the exception

System.out.println("Can't divide by Zero!");

}

}

}




catch (ArrayIndexOutOfBoundsException exc) {

// catch the exception

System.out.println("No matching element found.");

System.out.println("Fatal error


program terminated.");

}}} o/p:

4 / 2 is 2

Can't divide by Zero!

16 / 4 is 4

32 / 4 is 8

Can't divide by Zero!

128 / 8 is 16

No matching element found.

Fatal error


program terminated.



Custom Exceptions

class own extends Exception{

own ()

{


String str=new String("Exception at own:Invalid exc");


System.out.println(str);

}

}

class chain{

public static void main(String args[])

{

String st1=new String(args[0]);


String st2="kccs";

try{

if(st1.equals(st2))


System.out.println("st1 & st2 are the same");


else


throw new own();

}

catch(own e)

{

System.out.println(e);

}}}



class own extends Exception

{

own(String str)

{

super(str);

}

//public String toString()

//{


//String str=new String("Exception at own:Invalid exc");


//System.out.println(str);

//return str;

//}

}

class chain{

public static void main(String args[]){


String str=new String("Exception at own:Invalid exc");

String st1=new String(args[0]);


String st2="kccs";

try{

if(st1.equals(st2))


System.out.println("st1 & st2 are the same");


else


throw new own(str);

}

catch(own e){

System.out.println(e);

}}}

class thr{

int a[]={0,1};

int b[]={0,1,2};

void show()throws Exception

{


for(int i=0;i<a.length;i++)

{


try{

System.out.println(a[i]/b[i]);

}

catch(Exception e){

System.out.println(e);

}

}

System.out.println(b[4]);

} //show()

}//class thr

class Throws{

public static void main(String args[]){


thr t1=new thr();

try{

t1.show();

}

catch(Exception e)

{

System.out.println(e);

}}}