Importance Of
Exception Handling In Java
INTRODUCTION
The
computer programs are used to solve many kinds of problems like
◦ File
management
◦ Data
management
◦ General
applications
◦ Web
related etc
The phases in general program
process are :
◦ Writing
the source code
◦ compilation
– for checking the syntax error
◦ execution
– for obtaining desired results
Phases in Program Process:
o At the time of execution, a program may fall under
abnormal state such as
§ opening a file , which was not yet created
§ retrieving the invalid data
§ choosing of invalid data format
§ stack over flow
etc
Ø To avoid the abnormal termination of program
execution, first identify the Exception state & then handle it by using
external code segment.
Ø Most of computer programming languages do not support
this feature
Ø Java is a high level programming language which
supports in built exception handling mechanism.
Exception handling in JAVA by using
five key words -- try, catch, finally, throw, throws
Ø In JAVA,
exception state is treated as an
object, and handled by using
o Exception class
o Throwable interface
The code sample of exception state in a java program is
Class sample {
public static void main(String ar[]) {
int a[]=new int[5];
a[5]=23;
// array index out of memory exception
System.out.println(“ the value of 6th
element in a =“ + a[5]);
}
}
• While executing the above code at line 4, exception
is raised and program terminated abnormally.
• The following code shows how an exception handled in
java using try and catch
Class sample {
public static void main(String ar[]) {
int a[]=new
int[5];
try {
a[5]=23;
// array index out of memory exception identified
}
catch{
System.out.println(e);//handling
mechanism applied here
}
System.out.println(“ the rest of the
program continued”);
}
}
• While executing the above code at line 5, exception
is raised and handled and program terminated normally.
No comments:
Post a Comment