0% found this document useful (0 votes)
2 views15 pages

Chapter 4 Exception Handling

Chapter 4 discusses Exception Handling in Java, detailing the types of errors (compile-time and run-time) and the concept of exceptions as conditions caused by run-time errors. It explains the processes of handling exceptions using try and catch blocks, the use of finally statements, and the creation of custom exceptions. The chapter includes examples demonstrating nested try blocks, multiple catch blocks, and the throws keyword for declaring exceptions in method definitions.

Uploaded by

karpevaishnavi08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Chapter 4 Exception Handling

Chapter 4 discusses Exception Handling in Java, detailing the types of errors (compile-time and run-time) and the concept of exceptions as conditions caused by run-time errors. It explains the processes of handling exceptions using try and catch blocks, the use of finally statements, and the creation of custom exceptions. The chapter includes examples demonstrating nested try blocks, multiple catch blocks, and the throws keyword for declaring exceptions in method definitions.

Uploaded by

karpevaishnavi08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Chapter 4 Exception Handling

CO 4 Implement program using Multithreading and Exception handling.

4.1 Errors and Exceptions

Beginner programmers are rarely able to successfully execute their programs in


first effort. Generally they commit while developing and typing programs.
These mistakes are called Errors. There are two types of errors

- Compile-time Errors

- Run-time

Errors

All the syntax errors are detected by Java compiler. These errors are called
compile-time errors. Until and unless we clear compile program, byte-code
(.class file) will not be created for the examples of compile-time errors are
semicolon missing, mismatch of braces, use of undeclared variables etc.

After compiling a java program successfully, byte code is generated and then
that byte code given to the interpreter and it runs this .class file. But even then
sometimes the program generates wrong output. This happens due to incorrect
logic. This is called logical error (This type of error is to be corrected by
programmer by correcting the logic).

Also, sometimes program terminates due to errors like divide by zero. Both
these situations are referred to run-time errors. Some common run-time errors
are divide by zero, accessing element which is out of bound of array, converting
invalid string to a number etc.

Exception is a condition caused due to occurrence of run time error. This may
be due to violation of rules of Java language or due to constraints of the java
execution environment. While executing a program if exceptional condition
(like divide by zero) occurs, exception object is created by the java run time
system and is thrown. Exception can also be generated manually by a program
code.

In java, Throwable class woks as root for java’s error and exception hierarchy
as shown in following figure.
One more difference in Error and Exception is that Error is a critical condition
that cannot be handled by program code whereas Exception is exceptional
situation that can be handled by program code.

Some common Java Exceptions are,

- ArithmeticException(Mathematical errors like divide by 0)

- ArrayIndexOutOfBoundsException (try to access bad array index)

- ArrayStoreException (try to store wrong type in array)

- NegativeArraySizeException (array creation with negative size)

- FileNotFoundException (try to open file which does not exist)

- IOException (general Input/ Output failure)

- NullPointerException (try to reference a null object)

- IllegalArgumentException (illegal argument while invoking method)

- NumberFormatException (when conversion between strings and numbers fail)

- OutOfMemoryException ((not enough memory to allocate new object)

- SecurityException (applet tries to perform operation which is not allowed by


browser’s security setting)

- StackOverFlowException (system runs out of stack space)

- StringIndexOutOfBoundException (try to position in a string)

These are built-in exceptions


How Exceptions are occurred in java

class WithoutException
{
public static void main(String args[ ])
{
int p, q, r, s;
p = 30;
q = 3;
r = 3;
s=p/(q-r);
System.out.println("Result is "+s);
System.out.println("At the end of try block");
System.out.println("You should not divide a number by 0");
System.out.println("At the end of catch block");
System.out.println("At the end of main method");
}
}
4.1.1 Process of handling exception

If exception object is not caught and handled properly, program displays error
message and terminates its execution abruptly. If we want to execute remaining
part of the program (in such situation), we should handle the exception thrown
by the program. This process involves various tasks as,

- Find the problem (Hit the exception)

- Inform that error has occurred (Throw the exception)

- Receive error information (Catch the exception)

- Take corrective action (Handle the exception)

This can be achieved through two blocks -one for detecting error situation &
throwing the exception and other for catching the exception & taking suitable
action. These two blocks are referred as try block and catch black respectively.
They are shown in following figure.

Syntax for defining try block and catch block is given below.

try
{
Statements that may generate/cause exception
}
catch(Exception-type obj-name)
{
Statements for processing the caught exception
}
int a[]={1,2,3};
try
{
s=p/(q-r);//generate exception ArithmeticException
System.out.println(a[4]);
System.out.println(s);
}
catch(Exception e)
{
System.out.println(“divide by zero”);//handle
}

Try block

 We can use keyword try for defining a ‘try block’ and keyword catch for
defining ‘catch block’.

 Java try block is used to enclose the code that might throw an exception.
It must be used within the method.

 If an exception occurs at the particular statement of try block, the rest of


the block code will not execute. So, it is recommended not to keeping the
code in try block that will not throw an exception.

 It is mandatory to have at least one ‘catch block’ immediately after ‘try


block’.

 We may write multiple statements (those may cause exception) in try


block.

Java catch block

 Java catch block is used to handle the Exception by declaring the type of
exception within the parameter.
 The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach
is to declare the generated type of exception.
 The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
 Multiple statements may also be written in catch block for handling the
caught exception.

As observed in the above syntax, catch block looks like a method accepting one
parameter. If this parameter matches with the thrown exception object,
statements in the catch block are executed. Otherwise default exception handler
of java run-time environment will terminate the program execution.

Example 1:

class ExceptionEx1
{
public static void main(String args[ ])
{
int p, q, r, s;
p = 30;
q = 3;
r = 3;
try
{
s=p/(q-r);
System.out.println("Result is :"+s);
System.out.println("At the end of try block");
}
catch(ArithmeticException e)
{
System.out.println("You should not divide a number by 0");
System.out.println("At the end of catch block");
}
System.out.println("At the end of main method");
s=p/(q+r);
System.out.println("Result is :"+s);
}
}

Example 2:
class ExceptionEx2
{
public static void main(String args[ ])
{
int a[]={12,34,44,14};
int i;
System.out.println("Array elements are:");
try
{
for(i=0;i<8;i++)
{
System.out.println(a[i]);
}
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Thank you for using this program");
}
}

4.1.2 Nested try blocks

We may use try block within another try block. This concept is called nested
try block. Each try block requires at least one matching catch block.

Syntax:

try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}

Example:

class ExceptionEx3
{

public static void main(String args[ ])

int a[]={12,34,44,14};

int i, p, q, r, s;

p = 30;

q = 3;

r = 3;

try //outer try

System.out.println("Array elements are:");

for(i=0;i<=4;i++)

System.out.println(a[i]);

try//inner try

s = p/(q-r);

System.out.println("Result is "+s);

System.out.println("At the end of try block 2");

catch(ArithmeticException e) //inner try

System.out.println("You should not divide a number by 0");


System.out.println("At the end of catch block for try block 2");

catch(ArrayIndexOutOfBoundsException e) //outer try

System.out.println("Accessing out of bound array element");

System.out.println("At the end of catch block for try block 1");

System.out.println("At the end of main method");

}4.1.3 Multiple catch blocks for single try block

It may happen that statements in try block may create different exceptional

situations. So, a single try block may have multiple catch blocks for catching

different exception objects for different exceptional situations. An example

program is shown below.

try

catch(Exception_type1 e)

{------}

catch(Exception_Type2 e)

{---------}

catch(Exception_type3 e)

{----------}
Example:

class ExceptionEx4
{
public static void main(String args[ ])
{
int a[]={12,34,44,14};
int i, p, q, r;
p = 30;
q = 3;
r = 3;
try
{
a[5] = p/(q-r);
System.out.println("Result of division is stored in array");
}
catch(ArithmeticException e)
{
System.out.println("You should not divide a number by 0");
System.out.println("At the end of catch block 1");
}
catch(ArrayIndexOuyOfBoundsException e)
{
System.out.println("hiii");
}
System.out.println("At the end of main method");
}
}
4.1.4 Using finally statement

We may have a finally block after all the catch blocks (or even we may have try
block immediately followed by finally block). The finally block is always
executed regardless of whether the exception is thrown or not. It may happen
that there are multiple catch blocks, exception is thrown by try block and not a
single catch block is able to catch the exception. In such situation also, finally
block is executed. Even if any catch block is executed, finally block is also
executed. These characteristics can be easily figured out in the following figure.
Figure 4.3: finally block in Exception Handling

Syntax of try catch and finally

try
{
- try
- {
- -
} -
catch(Exception_Type e) -
{ }
-
- finally
} {
finally -
{ -
- }
-
}
Due to all these characteristics of finally block, it is generally used to perform
housekeeping operations like closing file handles, freeing the allocated
resources etc.
Following example program shows methods that exits in different ways, but
each executes their finally block.
Example:

class ExceptionEx6
{
static void method1(int x, int y)
{
int z;
try
{
z = x/y;
System.out.println("Result of division is: "+z);
}
catch(ArithmeticException e)
{
System.out.println("You should not divide a number by zero");
}
finally
{
System.out.println("Finally block is always executed");
}
}
public static void main(String args[ ])
{
method1(10,5);
method1(20,0);
}
}
4.1.7 throws keyword

If a method is capable of causing an exception, which it does not handle, this


must be specified in the method definition so that callers of this method can
handle such exception at their level. This can be done by using throws clause in
the method definition. We may include multiple exceptions (those are possible
to occur while executing the method) in the throws clause.
Syntax for using throws clause is as follows

return-type method-name(parameter-list) throws exception-list


{
// method body
}

Example:

class ExceptionEx7
{
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared
to be thrown
Explanation: In the above program, we are getting compile time error because
there is a chance of exception if the main thread is going to sleep, other
threads get the chance to execute main() method which will cause
InterruptedException.

Example with throws

class ExceptionEx7
{
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}

4.1.5 Creating own exception

There are various built-in exceptions in java which can handle most common
exceptional situations. But there is a need to create our own exceptions for
handling exceptional situations specific to applications under development. This
facility is provided by java.
For doing so, we have to create a subclass of Exception class (Exception class
is already a subclass of Throwable class. The new subclass automatically
inherits all the methods of Throwable class such as fillInStackTrace( ),
getCause( ), getLocalizedMessage( ), getMessage( ), initCause( ). Apart from
this, we may also create new methods.
Once the exception subclass is created, we may throw this new exception ny
using keyword throw with following syntax.

throw new exception_subclassname;

Following example programs show how we can create our own exception and
throw it.
Example 1:
class MyException1 extends Exception
{
MyException1(String message)
{
super(message);
}
}
class UserDefined1
{
public static void main(String args[ ])
{
try
{
throw new MyException1("This is user-defined exception");
}
catch(MyException1 e)
{
System.out.println("Caught Exception");
System.out.println(e.getMessage( ));
}
}
}

Example 2:
import java.io.*;
class MyException2 extends Exception
{
MyException2(String message)
{
super(message);
}
}
class UserDefined2
{
public static void main(String args[])throws IOException
{
String name="0125";
String pass="Bvjniot0125";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter password: ");
String str= br.readLine( );
try
{
if(pass.equals(str))
{
System.out.println("Password is correct");
}
else
{
throw new MyException2("password is incorrect");
}
}
catch(MyException2 e)
{
System.out.println("Caught Exception");
System.out.println(e.getMessage( ));
}
}
}

You might also like