Exception Handling in Java: Aimpoint Infosystem Pvt. LTD: Java Notes 2019
Exception Handling in Java: Aimpoint Infosystem Pvt. LTD: Java Notes 2019
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.
try
Exception
Occur
catch
Catch exception &
handled it
“try” :-
“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.
class ZeroDivide2
{
public static void main( String a[ ] )
{
int x = 15 , y = 0 , z ;
System.out.println(" START ");
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");
}
}
try {
for(int i =0;i < 5 ; i++)
System.out.println("The value of array is " +array[i]);
}
catch (ArrayIndexOutOfBoundsException e)
{ System.out.println("Array is out of Bounds");
}
}
}
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");
}
catch( Exception e)
{System.out.println("handeled");}
System.out.println(" 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.
Program Code
( try )
No Yes
Exception?
(catch)
No
Handler
Yes
finally block
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
“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
{ public MyOwnExceptionClass(String s)
{ super(s);
}
}
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 **** ");
}
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:
class ThrowsException1
{static void Method( ) throws MyException
{ throw new MyException( " This Is My Exception ");
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.