Recent

1.Try and Catch Blocks

try and catch Blocks – Exception Handling


On this page you will learn how to use the exception handler components – the try and catch blocks to write an exception handler.
try block
The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block.
In general, a try block looks like the following:


try
{
Code that may arise problems (Exception)
}

catch Block
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it.
You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
For example:


try
{
Code that may arise problems (Exception)
}

catch(ExceptionType name)
{

}

Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.
The catch block contains code that is executed if and when the exception handler is invoked.

***What we should write inside a catch block:
·         Print a non technical message to easily debug the program.
·         Never put any calculation inside a catch block which can result in another exception.
·         Call a function inside it or use recursion.
·         Close resources as work is not completed.

Some Important Points:
1.    The try-with-resources statement is a try statement that declares one or more resources.
2.    A resource is an object that must be closed after the program is finished with it.
3.    The try-with-resources statement ensures that each resource is closed at the end of the statement.
4.    Any object that implementsjava.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Programming Concepts related to try-catch Block:
Example 1: Catching an Exception using try-catch Block:


class Temp
{

public static void main(String[] s)
{

try
{
int x = 10/0;  //this statement will cause arithmetic exception
System.out.println(x);
}
catch(ArithmeticException e)  //catching arithmetic exception here
{
System.out.println(e + " >> please enter another value << ");
}
}}
Output:

Example 2: More than one catch-Block after single try-Block:


class Temp
{

public static void main(String[] s)
{
try
{
int x = 10/0;
System.out.println(x);
}

//Now the exception will be handled by suitable handler
catch(ArithmeticException e)
{
System.out.println(e + " >> please enter another value << ");
}
catch(ArrayIndexOutOfBoundsException ee)//second catch block
{
System.out.println(ee + "Second catch block");
}
}}
Output:

Example 3: catching multiple exception with single catch-block


class Temp
{
public static void main(String[] s)
{

try
{
int x = 10/s.length;
System.out.println(x);

int z[] = new int[s.length];
z[10] = 100;
}
catch(ArithmeticException  |  ArrayIndexOutOfBoundsException  e)
{
System.out.println("Mixed Exceptions aka multiple exceptions");
}
}}

/*Output
Mixed Exceptions aka multiple exceptions
*/



Example 4: Nested try-catch : We can put a try-catch block inside another try block

class Temp
{

public static void main(String[] s)
{
try
{
int x = 10/s.length;
System.out.println(x);

    try
    {
    int z[] = new int[s.length];
    z[10] = 100;
    System.out.println(z[10]);
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
    System.out.println("Array Index Out Of Bound Exception");
    }

}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception");
}
}}

/*Output
Arithmetic Exception
*/


Example 5: Using instanceof inside a catch-Block to identify an Exception and doing some according to exception occured


class Temp
{

public static void main(String[] s)
{

try
{
//s.length = 0 by default if we do not use command line argument
int x = 10/s.length;
System.out.println(x);

int z[] = new int[s.length];
z[10] = 100;
}

//catched the exception in parent Exception variable
catch(Exception e)
{
//using instanceof to identify an exception
if(e instanceof ArithmeticException)
{
System.out.println("Arithmatic exception");
}

if(e instanceofArrayIndexOutOfBoundsException)
{
System.out.println("Array Out Of Bound Exception");
}
}
}}
Output:

Example 6: Catching any exception with Exception class


class Temp
{

public static void main(String[] s)
{
try
{
int x = 10/s.length;
System.out.println(x);

int z[] = new int[s.length];
z[10] = 100;
}

catch(Exception e)
{
System.out.println("I can catch any type of exception");
}
}}

/*Output
I can catch any type of exception
*/


Exception handling in java is one of the powerful features of Java to handle the runtime errors so that normal flow of the instruction can be maintained.
There are 3 types of error:
1.    Syntax error: This error comes at compile time and appropriate action taken.
2.    Logical error: compiling and running but the result is not up to the mark.
3.    Runtime errors: These errors are most dangerous types of errors. These errors occur at client side due to mismatch or wrong entered data. To handle this type of runtime errors, Java introduced the concept of exception handling.
What is an Exception?
Exception means an “exceptional event” or we can say that Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
The Java programming language uses exceptions to handle errors and other exceptional events.

What is “throwing an Exception”?
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

What is Exception Handling?
Exception Handling is a way to handle these exceptions so that normal flow of instructions can be maintained.
           Process ——-> Abnormal condition ——-> condition handled exceptionally.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.
·         The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler.
·         The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called.
·         When an appropriate handler is found, the runtime system passes the exception to the handler.
·         An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.
What happens if it fails to find any appropriate handler?
The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler the runtime system and the program terminates.

Advantage of Exception handling:
1) Program termination due to exceptional events can be ignored.
2) We can easily debug a Java program by using custom exceptions.
Exceptions are of two types:
1) Checked exceptions: The classes that extendThrowable class except RuntimeException and Error are known as checked exceptions. For Example: IOException. These exceptions are known to compiler
2) Unchecked Exceptions: The classes that extendRuntimeException are known as unchecked exceptions. For Example: ArithmeticException. These exceptions are unknown to compiler.

Most common conditions when the exception can occur: Most of the time exceptions occur when the byte code of Java program goes outside the boundary of JVM
1) To accessing the database
2) To access files: for the purpose of reading data from file and writing data to a file.
3) To access something on network
There are five main keywords related to Exception handling we will learn in depth:
1) try
2) catch
3) finally
4) throw
5) throws

No comments:

Post a Comment

Bug-dbug Designed by Bugdbug - Developed by Belson Raja Copyright © 2016

Theme images by Bim. Powered by Blogger.
Published By Bugdbug India