Material_79a23ca6-4ffc-4b66-a182-62eeb2f76f60
Material_79a23ca6-4ffc-4b66-a182-62eeb2f76f60
=> Usually we believe that a complied program is error free and will always execute
successfully, but in few cases the program can terminate while it is executing.
=> For instance the program tries to modify a read-only file or it tries to open a file that does not
exist in the system. Such cases are known as “exceptions” in Java.
=> The exception results in an abnormal execution and it may lead to abnormal termination of
the program.
=> An exception is an indication of problem that occurs during a program’s execution, it usually
signals an error.
=> Although exceptions occur infrequently, we must be careful to handle such cases while
writing the code will always be executed.
Types of Exceptions:
=> In Java, all kinds of error conditions are called exception.
=> Errors can be broadly classified into two categories namely Compile-time errors and Run-
time errors.
Compile-time errors:
=> 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 to
create the “.class” file.
=> Example of some common syntax errors are missing semicolon, use of undeclared variable,
wrong spelling of identifier or keyword and mismatch bracket.
=> Compile-time errors are usually the mistakes of a programmer and it won’t allow the
program to compile unless they are solved.
=> Note: In the field of computer science “Exit code” or “Exit Status” indicates whether the
command or a program executed successfully or not. Code “0” indicates that the command
executed successfully whereas code “1” indicates that 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
and we will get a “.class” file.
=> However this does not guarantee that the program will execute as per our expectations.
1
=> The java.lang and java.io package contains a hierarchy of classes dealing with various
exceptions.
Exception Class Condition resulting in Example
Exception
ArrayIndexOutOfBoundsExcepti An attempt to access the Int a[]=new int[4];
on array element with an index a[13]=99;
value that is outside the
range of array.
ArithmeticException An attempt to divide any Int a=50/0;
number by 0
FileNotFoundException An attempt to access a non-existing file
NullPointerException An attempt to use null in a String s=null;
case where an object is System.out.println(s.length());
required
NumberFormatException A attempt to convert string String s=”xyz”;
into a number type Int i=Integer.parseInt(s);
PrinterIOException An I/O error has occurred while printing
Exception Handling:
=> Exception handling is an object-oriented technique for managing errors.
=> Java uses keywords like try, catch and finally to write an exception handler.
=> The keywords try, catch and finally are used in the presence of exception, these keyword
represent block of statements.
=> A try block contains the code that may give rise to one or more exceptions.
=> A catch block contains the code that is intended to handle exceptions of a particular type
that were created in the associated try block.
=> A finally block is always executed before the programs ends, regardless of whether any
exceptions are generated in the try block or not.
The try block:
=> The try statement contains a block of statements within the braces. This is the code that we
want to monitor for exception.
=> A try block may give rise to one or more exceptions.
Syntax:
try
{ //set of statement that may generate one or more exception }
The catch block:
2
=> The catch block must immediately follow the try block.
=> It contains the code that is to be executed to handle an exception.
=> The catch block is an exception handler, for a single try block there can be one or more
catch blocks.
Syntax:
Try
{ //statement that may generate exception }
Catch(Exception_Type Exception_object
{ //code to handle the exception }
=> A catch block consists of the keyword catch followed by a single parameter. Multiple Catch
Block:
=> In a single program multiple exceptions can occur.
=> If the try block throws several different kinds of exceptions, we can write multiple catch
blocks, each handling a specific type of exception. The finally block:
=> The finally block is generally used to clean up at the end of executing a try block.
=> We use a finally block 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.
=> A finally block is always executed , regardless of whether or not exceptions are thrown
during the execution of the associated try block
=> A finally block is widely used if a file needs to be closed or a critical resource is to be
released at the completion of the program.
Syntax:
Finally
{ // clean up code to be executed last. }
The throw statement:
=> The throw keyword is used to explicitly throw an Exception object.
=> In the example programs that we have seen so far, the JVM created an exception object and
was throwing it automatically. For example, an object of ArithmeticException was created
when we try to perform a divide by zero operation and it was thrown automatically by the
JVM.
=> Java does provide mechanism to create an Exception object and throw it explicitly.
=> The object that we throw must be of type java.lang.
=> Throwable, (object of Throwable class or any of its sub-classes) otherwise a compile error
occurs.
=> The syntax to throw an exception object is as follows: throw exception_object;
The throws Clause:
3
=> We have explored the try-catch-finally blocks, the programs we discussed so far were simple
programs that didn’t involve the use of methods.
=> Few questions may arise like what will happen 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:
=> Write a try-catch block within the method or a constructor that may generate an exception.
=> Invoking a method (that may generate exception or constructor within a try block.
=> A throws clause can be used in a method declaration or constructor declaration to inform
that the code within the constructor or method may throw an Exception.
=> It also signifies that there is no catch block within the method that can handle the exception.
=> The throws keyword is used with the declaration of method.
Method_Modifiers return_type method_Name (parameter) throws Exception list…..
{ //body of the method }
=> A method can throw multiple exceptions.
=> Each type of exception that a method can throw must be stated in the method header.
Creating Custom Exception:
=> Java allows creating our own exception classes according to application-specific problems.
=> For instance, we are writing a program to generate a mark sheet in which the user is asked
to enter marks of different subjects.
=> The marks must be in the range of 0 to 100.
=> Suppose if the user enters negative marks or the value is above 100 then program must
generate exception.
=> We can create user-defined exceptions by creating a subclass of Exception class
Advantages of Exception Handling:
=> It allows us to maintain normal flow of program. In the absence of exception handling, the
flow of program is disturbed.
=> It allows writing separate error handling code from the normal code.
=> Error types can be grouped and differentiated within the program.
=> Assertions can be used to debug the program before deploying it to the clients.
=> It provides an easy mechanism to log various run-time errors while executing the program.