Monday 15 July 2019

Exception handling in java | java Exception - Online Help

Exceptions are generated when we recognized an error condition during the execution of a program. Java includes a system for running exceptions by tracking the potential for each method to throw a specific exception.

Exception handling fundamental(Introduction):

An exception is an event, which occurs during the execution of a program, that an interrupt the normal flow of a program's instruction. In other words, the exception is generated when a recognized condition usually an error condition arises during the execution of a method.Java includes a method for running the exceptions, by tracking the method to throw a specific exception.

For each method that could throw an exception, your code must report the java compiler that it could throw that exact exception. The compiler marks that method as potentially throwing that exception, and then need a code calling the method to handle the possible exception.

Exception Handling Mechanism:

Exception handling in java refers to the java's handling of the run time errors. An exception is an object that is generated at the runtime to describe a problem encountered during the execution of a program.

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. The general form of exception handling is :

try
{
//  block of code monitor an error
}
catch(exception type1 exceotionobj)
{
//  exception handler for exception type1
}
catch(exception type2 exceotionobj)
{
//  exception handler for exception type2
}
//...................
finally
{
//  block of code to be executed before try block ends.
}

Briefly, here is how they work program statement that you want to monitor for exception contained within the try block. If an exception occurs within the try block, it is thrown and will be catched the exception in the catch block and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system.

To manually throw an exception, use the keyword throw. Any exception that is thrown out of the method must be specified as such by a throws clause. Any code that must be executed before a method return is put in a finally block. This is called an "Exception handling mechanism".

Classification of exception handling:

Java has a number of built-in classes for handling the exceptions. The class throwable is at the top of the exception class hierarchy. Throwable class is two subclasses that partition exception into two types. One exception and other is an error.

Error:

Error is an exception that is not expected to be catch under normal circumstances by your program. It is used by the run time system to indicate error having to do with the run-time environment, itself. Stack overflow is an example of error. There are basically three types of errors in the java program:

Compile-time error: error which occurs due to syntax or format is called compile-time error. These errors are detected by java compiler at compilation time.

Runtime error: These are an error that computers inefficiency. Insufficient memory to store data or inability of the microprocessor to execute some statement is examples of runtime errors. Runtime errors are detected by JVM at runtime.

Logical error: These are the errors that occur due to the bad logic in the program. These errors are rectified by comparing the output of the program manually.

ALSO READ: packages in java

Built-in Exception:

Java has several built-in Exception. The most commonly used exceptions are as follow:

Exception class
Description
ArithmeticException
Arithmetic error, such as division-by-zero.
ArrayIndexOutOfBoundException
The array index is out of bounds, or wrong index value.
ArrayStoreException
Assignment of an array element of an incompatible type (wrong type of data in an array).
IllegalArgumentException
The illegal argument used to invoke a method.
IllegalStateException
Environment or application is in an incorrect state.
IndexOutOfBoundException
Some types of the index are out of bounds.
NullPointerException
Invalid use of a null reference.
NumberFormatException
A number is in an illegal format.
StringIndexOutOfBoundException
A string index is out of bound.
ClassNotFoundException
A class can not be found.
IllegalAccessException
Access to a class is defined.
NoSuchFieldException
A request field does not exist.
NoSuchMethodException
A request method does not exist.
InterruptException
A thread has been interrupted.


Using try and catch:

In order to handle the exception, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch. The try statement contains a block of the statement. A try block can be written and if a problem occurs during its execution, control proceeds to the appropriate catch block.

Note: The catch block is skipped if no exception is raised in the try block.

Simplest form of the catching an exception is as follows:

try
{
//statement for monitoring the errors
}
catch(exception excepobject)
{
//exception-handling
}

Sample program:

class excepdemo
{
public static void main(String args[])
{
int a=10,b=0,x;
try
{
x=a/b;
}
catch(ArithmeticException e)
{
System.out.println("division-by-zero);
}
}



Multiple catch clauses:

In some clause, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clause, catch catching the different type of exception.when an exception is thrown, each catch statement is inspected in order and the first one whose type matches that of the exception is executed. After one catch statement executes, the other is bye passed and execution continues after the try/catch block. The general form is :

try
{
//statement for monitoring the errors
}
catch(Exceptiontype1 excepobj)
{
//
}
catch(Exceptiontype2 excepobj)
{
//
}

Sample program:

class mulcat
{
public static void main(String args[])
{
int a[]={2,8};
int b=4;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("division by zero");
}
catch(ArrayIndexOutofBoundException e)
{
System.out.println("invalid index");
}
catch(ArrayStoreException e) 
{
System.out.println("wrong datatype");
}
}
}

Nested try Statement:

The try can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement's catch handlers are inspected for a match. This continues until one of the catch statement succeeds or until all of the nested try statement are exhausted. If no catch statement matches, then the java run-time system will handle the exception.



Throw Clause:

The throw statement is used to explicitly throw an exception .i.e; if any error occurred in the try block then it throws the exception to the catch block. The general form of the throw is as follow:

throw throwableinstance;

here,throwableinstance must be an object of the type throwable or a subclass of throwable. Simple types such as int or char, as well as non-throwable classes such as string and object, cannot be used as an exception. There are two ways you can obtain a throwable object: using a parameter into a catch clause or creating one with the new operator.

The flow of execution stops immediately after the throw statement; any subsequent statement is not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a  match, control is transferred to that statement. If no matching catch is found, Then the default exception handler halts the program and print the stack trace.

Sample program:

class throwdemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("caught inside demoproc");
throw e;   //rethrow the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("recaught:"+e);
}
}
}

Throws Clause:

The throws clause is used to list the type of exceptions that are thrown by the method. This is necessary for all the exceptions, except those of type error or run time exception and any of their subclasses. We can include throws clause in the method declaration. The general format of throws is as follows:

return-type methodname(parameter_list) throws exception list
{
//body of the method
}

Sample program:

class throwsdemo
{
static void throw1() throws IllegalAccessException
{
System.out.println("Inside throw1")'
throw new IllegalAccessException("demo");}
public static void main(String args[])
{
try
{
throw1();
}
catch(IllegalAccessException e)
{
System.out.println("caught:"+e);
}
}
}


Also Read: Font class in java

Finally clause:

Finally block creates a statement that will be executed after a try or catch block has been computed. The finally block will execute whether or not an exception is thrown. The finally clause is optional. 
The general form is:

finally
{
//statement to be executed before any try block ends
}

Sample program:

class finally
{
public static void main(String arg[])
{
int a[]={2,8};
int b=4;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("division-by-zero");
}
catch(ArrayIndexOutOfBoundException e)
{
System.out.println("invalid array index");
}
finally
{
int y=a[1]/a[0];
System.out.println("y="+y);


}
}
}

No comments:

Post a Comment