Chapter 10 WEIGHTAGE
EXCEPTION HANDLING 6 MARKS
EXCEPTION
An exception is an indication of a problem that occurs during a program’s execution.
An exceptional may lead to abnormal termination of the programs. The program will execute as
unexpected.
o So exception results into following one:
It results in an abnormal execution
It may lead to abnormal termination of the program.
In java all kind of error conditions are called exceptions. In OOP terminology, exception is refers
to error condition. Exceptions and errors are the same thing.
In the following cases can be known as “exceptions”
o A program of downloading a web page is executed in a computer where there is no internet connection.
o A program to open a file that does not exist in the system.
o To divide any number with zero and get unexpected result.
Exception is
o an indication of a problem that occurs during a program’s execution
o all kinds of errors conditions..
Exception slows a program to continue executing as if no problem has been encountered.
Exceptions notify the user of the problem before terminating in an uncontrolled manner.
Exceptions generally show error message.
Exception must be handled carefully while writing the code.
Error can be broadly classified into two categories namely compile time error and run-time errors.
COMPILE TIME ERRORS
Source code is known as basic instructions of any programming language.
Object code is known as the instructions which can be implemented by a computer.
Compiler is used to convert basic instructions of any programming language to the instructions which
can be implemented by a computer.
o A compiler is used to convert source code into object code.
If there is a syntax error in the program we will get a compilation error and will not be able tocreate
the “.class” file.
Example of some common syntax errors are as under:
o Missing of “,” (comma)
o Missing of “;” (semi-colon)
o Use of undeclared variable
o Wrong spellings of identifier or keyword
o Mismatch of bracket
Java compiler show if there is an during compilation:
o The line number where error has occurred
o The type of errors
Compile time error are usually the mistake of programmer.
Presented by Nuzhat Ibrahim Memon 1
Exit code or exit status indicates whether the command or the program has been executed
successfully or not in the field of computer science.
Exit code 0 indicates that the command execution is successful
Exit code 1 indicates some problem occurred while executing the command.
RUN TIME ERRORS
If there are no syntax errors in the source code then the program will compile successfully andwe will
get a “.class” file.
However this does not guarantee that the program will execute as per our expectations.
A number when divided by zero leads to infinity as a result
Here program will be compiled successfully but will generate unexpected output due to
Arithmetic Exception.
There are corresponding exception classes in java.
The java.lang and java.io package contains a hierarchy of classes dealing with various
exceptions.
EXCEPTION HANDLING
Java uses keyword like try, catch and finally to write an exception handler.
We try to ensure while performing exception handling:
o The program does not terminate abruptly
o The program does not generate unexpected output
Exception handling allows us to maintain normal flow of program
Advantage of exception handling
o It allows us to maintain normal flow of program
o It allows writing separate error handling code from the normal code
o Error types can be grouped and differentiated within the program
o Assertions can be used to debug the program before deploying it to the clients.
o It provides an easy mechanism to log various run time errors. While executing the program.
o The flow of program is not disturbed.
The keyword try, catch and finally are used in the presence of exceptions.
A try block contains the code that may give rise to one or more exceptions.
o Try contain the code where we want to monitor for exceptions
o Try block contain the part of program that may lead to runtime errors.
o Try block should be the code that may generate exception be written
o Catch or finally block has to be there after try block
o Following can be in try statement
Minimum one catch block
More than one catch block
Finally block
A catch block contains the code that is intended to handle exceptions of a particular type that is created
in the associated try block.
o Any number of statements to handle exception should be within a catch block
o When a try block does not generate an exception and you have included multiple catchblocks,
then no catch block executes.
o Try bl0ock does the catch block immediately follow
Presented by Nuzhat Ibrahim Memon 2
o A catch block consists of the keyword catch followed by the following one parameter
A finally block is always executed before the programs end, regardless of whether any
exceptions are generated in the try block or not.
o Finally block is generally used to clean up after executing a try block
o Finally block do we use when we want to be sure that some particular code is to be run,
no matter what exceptions are thrown within the associated try block.
o Finally block widely used at the completion of the program
if a file needs to closed
if a critical resource is to be released
o Finally block must always to be followed by try block rather than a catch block
o Finally block is associated with a particular try block located immediately catch block
If finally and catch blocks are not positioned correctly, then the program will not compile
Try block throws several different kinds of exceptions, we can write multiple catch blocks, each
handling specific type of exception.
Default block has to be placed at the end of all catch blocks, when there are multiple catch block in a
program.
Syntax of default catch block catch(Exception e)
Multiple try block can be nested.
If the program has no exception handler then program will be terminated
List of few widely observed exception
EXCEPTION CLASS CONDITION RESULTING IN EXCEPTION EXAMPLE
ArrayIndexOutOfBoundsException An attempt to access the array element int a[]=new int[4];
with an index value that is outside the a[13]=198
range of array
ArithmeticException An attempt to divide any number by 0 int a=13/0;
FileNotFoundException An attempt to access a non-existing file
NullPointerException An attempt to use null in a case where an String a=null;
object is required System.out.println(a.length());
NumberFormatException An attempt to convert string to a number String n=”ByteLand”
type int i= Integer.parseInt(D);
PrinterIOException An I/O error has occurred while printing
THE THROW STATEMENT
The throw keyword is used to explicitly throw an Exception object.
Java does provide mechanism to create an exception object and throw it explicitly.
JVM (Java Virtual Machine) creates an exception object and throw it automatically when throw
statement is not used.
The object we throw must be of type java.lang so that a compile error does not occurs.
Type of object that we throw must be java.lang.throwable
o Object of throwable class
o Object of any throwable class’s sub-classes
Syntax to throw an exception object throw exception_object;
When a throw statement is encountered, a search for matching catch block begins. Any
subsequent statements in the try or catch block are not executed.
o Catch search for matching begins when a throw statement is encountered
Presented by Nuzhat Ibrahim Memon 3
o Catch block is available to handle the exception object thrown explicitly in java.
There has to be catch block to handle the exception object thrown explicitly.
THE THROW CLAUSE
If an exception occurs in a method or a constructor, where will we place the try-catch blocks. There
are two alternate approaches to handle exceptions created by a method:
o Write a try-catch block within the method or a constructor that may generate an exception.
o Invoking a method (that may generate exception) or constructor within a try block.
A throw class can be used in a method declaration or constructor declaration to inform that the code
within the constructor or method may throw an exception.
Many exception can be thrown by a method
In header section of method each type of exception that a method can throw must be stated
Catch handler must be matching there if the method throws an exception object.
To throw is not needed if we are catching an exception type within the method
It also signifies that there is no catch block within the method that can handle the exception.
The throw keyword is used with the declaration of method.
A method that throws an uncaught, cheeked exception must include throws clause in its
declaration
A method can throw multiple exceptions.
CREATING CUSTOM EXCEPTIONS:
Java allows creating our own exception classes according to application specific problems.
For instance if the user enters negative marks or the value is above 100 as any mark of subject thenthe
program must generate an exception. Or user enters value of standard rather than 1 to 12
Such kind of exceptions are application specific.
Java does not provide built-in exception classes for application specific exceptions.
We can create user-defined exceptions by creating a subclass of exception classes.
These exceptions can be thrown explicitly using throws statements.
EXTRA
Throws statements can the exceptions be thrown explicitly
java.util.scanner class is used to accept input from the keyboard
nextInt() method of scanner class helps in reading input from the console.
To read integer input form the console the nextInt() method helps
Throws block is necessary to solve exceptions
Syntax of ‘if ‘ statement to check whether the value of variable ‘m’ is from 0 to 100 or not
If(m<0 || m>100)
SciTE is an editor to type the java programs
It is advisable to execute the program if the program access data from the keyboard
o From the SciTE editor and from the command prompt
A simple program be executed from the SciTE editor does not require user interaction
Presented by Nuzhat Ibrahim Memon 4