Sei sulla pagina 1di 14

AimPoint InfoSystem Pvt.

Ltd : java Notes 2019

Exception handling in java


Generally there are two types of error occurs in a program.

1. Compile time error:-


Whenever any syntax error occurs in a program at compile time , that program not get
compiled properly and java compiler doesn‟t create .class file and these types of error
called “compile time error”, and these types of error shows by the compiler and can be
easily repaired by Programmer.

Some common example of compile time errors :-

 Missing ; ( z = x + y )
 Mismatching of brackets . ( x + y – ( k – 10 )
 Misspelling of keywords and identifier . ( Int x ; )
 Undeclared variable .
 Misplace operator . ( z = a b )
 Assigning incompatible value ( float y = 13.6 ; )

2. Runtime error:-
Sometimes a program may compiled properly & also creating .class file , but not
executing properly so in this case always shows wrong output due to our wrong
logic .these types of error is called “runtime error”. And Run time errors doesn‟t
display by compiler. We can debug runtime errors in the testing of programs.

Some common example of run time errors:-

 Dividing any integer by 0. (Assigning ∞ value)


 Accessing element from out of bound of array.
Example
int x [ ]=new int[ 5 ] ;
x[10]=50;
 Assigning incompatible value in array.
Example
int X = Integer.parseInt( “215” ) ;
int X = Integer.parseInt ( “Hello” ) ; //invalid (cannot convert)
 Passing values in function but these are not in the range.
 Converting invalid string into number.
Example
int x ; x = ”215”; x = ”hello”;

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 1


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

Exception handling in java:-


Whenever any unexpected error comes at runtime this is called exception &
“exception handling” is a mechanism to handle these runtime errors.

In java whenever any runtimes errors comes at runtime java compiler


automatically create “Exception“(class) object & throws it. If “Exception“ object
is not caught and handled properly, in this case java interpreter display message
and program will be abnormally terminated. If we want to continue the program
with remaining code, we should try to catch these “Exception” object throws by
exception or error and should handled properly.

Steps for exception handling in java


 Hit the exception
 Throw the exception
 Caught the exception (catch)
 Handle the exception.

try
Exception

Occur

catch
Catch exception &
handled it

Exception handling managed in java by following keywords.

Constructs keyword statement keyword

try catch finally throw throws

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 2


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

“try” :-

 It is a block & containing statements in which error can be occurs.


 If once control come out of the “try” block using throwing the exception then
control doesn‟t comes to the “try” block.
 In a method multiple try blocks and nesting of “try” block is also possible.

“catch” :-
 It is a block (in c++ it is a statement) & used to catch the exception which is throws by
“try” block.
 “catch” block must be written just after “try” block.
 “try” block must be followed by at least one “catch” block.
 Multiple “catch” blocks can be associate with a single “try” block.
 “catch” block always take arguments of a “Exception” class ( or derived class of
“Exception” class).
 “catch” block executed, if it is receiving exception otherwise not executing.

Structure of exception handling


try
{
............
............
throw exception ;
..............
throw exception ;
..............
}
catch (Exception a)
{
..................
...................
}
catch(Exception b)
{........................
.......................
}

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 3


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

Types of exception in java

 Built in or compiler defined exception.


 User defined exception
Note:-all built in exception defined in “java.lang.Throwable” class (super
class) & “Exception” class (sub class)

Built – In Exception In Java ( Compiler Defined Exception Classes)


1. ArithmeticException (division by zero)
2. ArrayIndexOutOfBooundsException (bad array index)
3. ArrayStoreException (wrong type of data into array)
4. FileNotFoundException (attempt to access is not exist file)
5. IOExeption (failure reading from file)
6. NullPointerException (reference point to the null object)
7. NumberFormatException (conversion bit string and number)
8. OutOfMemoryException (not enough memory for new data)
9. StackOverflowException (system runs out of stack memory)
10. StringIndexOutOfBooundsException (bad string character)

//WAP to show exception in case of zero divide


class ZeroDivide1
{
public static void main( String a[ ] )
{ System.out.println("Start");
int x = 15 , y = 0 ;
int z;
z= x / y ;
System.out.println(" Division = "+z ) ;
System.out.println("End");
}
}

//WAP to handeled exception in case of zero divide problem

class ZeroDivide2
{
public static void main( String a[ ] )
{
int x = 15 , y = 0 , z ;
System.out.println(" START ");

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 4


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

try
{
z= x / y ; // automatically throw "ArithmeticException"
System.out.println(" Div = "+z);
}

Catch (ArithmeticException e)
{
//System.out.println(" Sorry ..... Divide By Zero " ) ;
//or//
//System.out.println(e.getMessage() ) ; //msg by getMessage() method
//or//
e.printStackTrace( ) ;// for display detail msg

}
System.out.println("END");
}
}

//WAP to show handle exception in case of zero divide


class ZeroDivide3
{
static void divide(int x ,int y )
{
int z ;
try
{
z= x / y ; // automatically throw "ArithmeticException"
System .out .println("\n Z= " + z) ;
}
catch(ArithmeticException e)
{
System.out.println(" Sorry ..... Divide By Zero " ) ;
System.out.println(" good luck for next time .... ");
}
}

public static void main( String a[ ] )


{
divide( 12 , 4);
divide( 12 , 0 );
divide( 30 , 0 );
divide( 15, 3 );
}
}

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 5


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

//WAP to show the exception of invalid format of command line input


class CmdException
{ public static void main( String a[ ] )
{
int x ;
x = Integer . parseInt(a[ 0 ] );
System.out.println(" POWER = "+ Math . pow( x , 5 ) );
}
}
//run1 javaCmdException 2 ( output POWER = 32.0)
//run2 javaCmdException ten (generate "NumberFormatException" exception )
//run3 javaCmdException (generate "ArrayOutOfBoundException" exception )

//WAP to show the exception of invalid format of command line input


class CmdException1
{ staticint x ;
public static void main( String a[ ] )
{
try
{
x = Integer.parseInt(a[ 0 ] );
System.out.println(" Square = "+ Math.pow(x,2) );
}
catch(ArrayIndexOutOfBoundsException d)
{
System.out.println(" plz enter input at command line" );
}
catch(NumberFormatException n)
{
System.out.println(" invalid input at command line" );
System.out.println(" plz again enter valid numeric input" );
}
}
}

//WAP to check ArrayIndexOutOfBounds Exception in Array


public class ArrayBound
{ public static void main (String args[ ])
{
int array[ ]={10,20,40};

try {
for(int i =0;i < 5 ; i++)
System.out.println("The value of array is " +array[i]);
}

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 6


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

catch (ArrayIndexOutOfBoundsException e)
{ System.out.println("Array is out of Bounds");
}
}
}

Nested try block in exception handling


Nesting of try block is possible in programming and separate catch block will be
executed with separate try block.

Syntax :
try
{ ............
try
{
..............
}
catch (Exception e )
{
...................
}
....................
}
catch(Exception e)
{........................
}
//WAP to demonstrate nested "try" block
class NestedTry
{ public static void main(String args[])
{ System.out.println(" START ");
try
{ int z=20/4; // if exception raise then control goes to the outer catch block
try{ System.out.println("going to divide by zero");
int b =40/0;
}
catch(ArithmeticException e)
{System.out.println("divided by zero");}
try
{ int a[ ]=new int[5];
a[8]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("out of bound array ");}
System.out.println("other statement");
}

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 7


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

catch( Exception e)
{System.out.println("handeled");}
System.out.println(" END ");
}
}

/* run 1 ) if exception raise in outer try block ( int z = 20/0 ;)


START
handeled
END

run 2 ) if exception raise in both inner try blocks


START
going to ........
divided by ....
out of bound......
other statement
END */

„finally‟ block:-
 It is a keyword & used to create a block and finally block coding will be
always executes whether exception is occurred or not (or exception is
handled or not).
 It must be written just after try block (without catch block) or after all catch
statements.

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 8


AimPoint InfoSystem Pvt. Ltd : java Notes 2019
Try Try
{ {
............ ............
............ }
} catch
finally {...........
{........... ...........
........... }
} catch
{.............
}
finally
{...................
}
Note: - do not write catch block after
finally block.

 It is used to write cleanup statements and used to perform some housekeeping


statements like closing of files or releasing system resources.

Program Code

( try )

No Yes
Exception?

(catch)

No
Handler
Yes

finally block

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 9


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

//wap to demonstrate finally block


public class MyFinallyBlock
{ public static void main(String[] a)
{ try
{
int i = 10/0;
}

catch(ArithmeticException ex)
{System.out.println(" Dividing By Zero");
System.out.println("Inside 1st catch Block"); }
finally
{ System.out.println("Inside 1st finally block"); }

//--------------------------------------------

try
{
int i = 10/10;
}
catch(Exception ex)
{ System.out.println("Inside 2nd catch Block"); }
finally
{ System.out.println("Inside 2nd finally block"); }
}
}
User defined exception
Hierarchy of exception classes

Object

Throwable

Error Exception

UserDefinedException RuntimeError

Note :- all are classes.

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 10


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

 It means we can defined exceptions classes according to user requirement.


 User defined exception are classes, those are must be the subclass of
“Exception”class
 In user defined exception the method of “Throwable” can be override.
 Constructor can be defined in user defined exception.
 In user defined exception we can override toString() method of “Throwable”
class to display customized message.

“throw‟ :-

 It is a keyword & used to throw exception explicitly, and it must the object of
“Throwable” class or object of subclass of “Throwable” class.
 Compiler defined exception raise automatically & throws automatically whenever
any exception is occurred and it is implicit called. Where user defined exception
throw explicitly.
 After the encountering of throw statement this method will stop the execution &
occurred exception throw to the catch statements.

Syntax

throw ”Throwable” instance / object of subclass of “Throwable” class;


throw new Throwableinstance( ) ;

// WAP to demonstrate user defined Exceptions

class MyOwnExceptionClass extends Exception

{ public MyOwnExceptionClass(String s)
{ super(s);
}
}

public class Client


{
public static void main(String[] args)
{ int price = -120;
try{
if(price < 0)
{MyOwnExceptionClass o1= new MyOwnExceptionClass("Price should not be in
Negative you are entered -ve price");
throw o1 ;
}
else
System.out.println("Price is :"+price);
}

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 11


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

catch(MyOwnExceptionClass m )
{ System.out.println( m.getMessage( ) ) ;
}
}
}
/*3. Write a Java Program to find the exception Marks Out of Bounds.
and Invalid Student name */
import java.util.Scanner ;
class StudentMarksException extends Exception
{
StudentMarksException( String temp)
{ super(temp);}
}
class InvalidNameException extends Exception
{
InvalidNameException( String temp)
{ super(temp);}
}
class Student
{ public static void main(String a[ ] )
{ int marks ;
String sname ;
try
{Scanner o1 = new Scanner( System.in ) ;
System.out.print( " Enter Marks Of Student(out of 100) : ");
marks = o1.nextInt( ) ;
if(marks > 100 )
throw new StudentMarksException( " Invalid Marks ");
else if(marks < 0 )
throw new StudentMarksException( " Invalid Marks ");
System.out.print( " Enter Name Of Student : ");
sname = o1.next( );
for( int i=0 ; i<sname.length( ) ; i++)
{char ch = sname.charAt(i);
if(Character.isAlphabetic(ch))
continue ;
else
throw new InvalidNameException( " InValid Name ");
}
System.out.println( " ****Valid Marks and Valid Name **** ");
}

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 12


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

catch(StudentMarksException s )
{ System.out.println ( s. getMessage( ) ) ; }
catch(InvalidNameException n)
{ System.out.println(n.getMessage( ) );
System.out.println(" plz again enter valid Name" );
}
}
}

“throws” keyword
 If any Method causing exceptions & it is not handled in this function then caller
function can guard themselves against exception using „throws‟ clause in the
function declaration.
 „throws‟ clause can throw any exception except „Error „and „RuntimeError‟
(because these are unchecked exception) & also cannot throw the subclasses of
these exception.
 All exception must be mention in the function declaration, separated by comma(,)
in “throws” clause if any exception is not mentioned in the list and if function raise
these exception then compiler gives error.(means program will be terminate.)
 Build in exception can be throw directly from the method without using “throws”
clause.

Syntax:

Returntype Methodname (para list) throws list of possible exceptions


{
......................
......................
}

//wap to demonstrate the use of “throws” clause

class MyException extends Exception


{ public MyException(String a )
{ super(a); }
}

class ThrowsException1
{static void Method( ) throws MyException
{ throw new MyException( " This Is My Exception ");

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 13


AimPoint InfoSystem Pvt. Ltd : java Notes 2019

public static void main(String a[])


{
System.out.println(" Before Try Block ") ;
try
{ Method( );
}
catch(MyException e )
{
System.out.println(e.getMessage( ) ) ;
}
System.out.println(" After Try Block " ) ;
}
}
// wap to demonstrate throw the compiler defined exception from any method without
//throws clause .

class ThrowsException
{
static void Method( ) // does not need to mention built in exception in "throws" clause
{
int x , y=12 , z[ ] ={ 2 ,3, 5 } ;
x = 12 / 0 ; //1
z[4]=25; //2
x=Integer.parseInt("five");//3
// only one statement get executed
}
public static void main(String a[])
{
System.out.println(" Before Try Block ") ;
try
{
Method( );
}
catch(ArithmeticException e )
{
System.out.println("Dividing By Zero" ) ;
}
catch(NumberFormatException e )
{
System.out.println(" Invalid Number " ) ;
}
catch(ArrayIndexOutOfBoundsException e )
{
System.out.println(" Array Out Of Bound " ) ;
}
System.out.println(" After Try Block " ) ;
}
}
Assignment:-WAP to define user defined exception for withdraw money from account and
it should raise whenever user withdrawing money more than balance.

Faculty : Sandeep Sir ( M.Tech ph : 9425007241) Page 14

Potrebbero piacerti anche