Exception Handling In Java

Exception handling can be defined as a mechanism of handling exceptions that can be occurred at run time. This mechanism is used to avoid malfunctions such as computer hanging, computer deadlock, runtime exception such as divide by zero, array out of bounds. Exceptions can be generated by the Java run-time system. Java Class Explation CLICKHERE

Exception handling Keywords in Java

Java Exception handling is managed by five keywords: try, catch, throw, throws and finally.

The general form of an exception handling

try {
//block of code to monitor for errors
}
catch(Exception Type1 exOb) {
//exceptiion handler for Exception Type1
}
catch(Exception Type2 exOb) {
// exception handler for Exception Type2
}
//……..
finally {
// block of code to be after try block ends
}

Exception Types

Exception Handling Types

try and catch exceptions

If the program stopped running and printed an error. To handle a run-time error, simply enclose the code that you want to monitor inside a try block, include a catch clause that specifies the exception type that you wish to catch.

The following program includes try and catch clause that processes the program divide by zero:

class Ex {
public static void main(String args[]) {
int d,a;
try { //monitor a block of code
d = 0;
a = 57/d;
System.out.println("This line will not printed");
}
catch(ArithmeticException e) { //catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

Output:

Division by zero.
After catch statement.

From the above program, we can notice that println() inside the try block is never executed. Once an exception is thrown program transfers out of the try block. Then the catch statement will be executed. That’s why “This line will not printed” was not displayed in the output. The goal of the catch clauses should be to resolve the exceptional condition and then continue on as if the error had never happened.

Multiple catch clauses in Exception handling

In some cases, more than one exception occurs in a single code we should use more than one catch clause to overcome the problem. Each catch clause consists of different types of exception.

multiple catch clauses program

//Demonstrate multiple catch statements.
class MultipleCatches {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println(" a = " + a );
int b = 50/a;
int c[] = { 1 };
c[50] = 33;
} catch(ArithmeticException e) { //first catch clause
System.out.println("Divide by 0 : " +e);
} catch(ArrayIndexOutOfBoundsException e) { //second catch clause
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

Output:

C:\madhanj>java MultipleCatches
a = 0
Divide by 0 : java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\madhanj>java MultipleCatches TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException: Index 50 out of bounds for length 1
After try/catch blocks.

In the above output, two exceptions displayed. The first catch clause executed when Arithmetic Exception(Divide by Zero) occurred. Second catch clause executed when Array Index outbounds.

Nested try Statement

A try block statement can be inside the block of another try block statement is known as Nested try Statement. In the nested try block if the try statement doesn’t have any particular exception. It will go to the next try statement this process continues until all try statements are exhausted.

sample example for nested try statement.

class NestTry  {
public static void main(String args[]) {
try {
int a = args.length;
/*If no command-line args are present,the following statement will generate a divide-by zero exception. */
int b = 33/a;
System.out.println("a = " +a);
try { //nested try block
/*If one command line arg is used,then a divide-by-zero exception
will be generated by the following code. */

if(a==1)
a = a/(a-a); //division by zero
/*If two command-line args are used,then generate an out-of-bounds execption. */
if(a == 2) {
int c[] = { 1 };
c[50] = 99; //generated an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds:" +e);
}
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " +e);
}
}
}

output

C:\madhan>javac NestTry.java
C:\madhan>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\madhan>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\madhan>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException: Index 50 out of bounds for length 1

throw Exception handling

With the help of throw statement we can throw an exception explicitly in our program. Bascically, the exceptions thrown by the Java run-Time system are being caught, but throw statement allows a program to throw an exception explicitly. General form of throw statement is:

throw ThrowableInstance;

ThrowableInstance must be an object of type Throwable or a subclass of Throwable. The flow of execution stops immediately after the throw statement. If the try block doesn’t have catch clause control transfer the statement. If no match occurs catch block is found.

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

output:

Caught inside demoproc.
Recaught : java.lang.NullPointerException: demo

The above program deals with the two times with the same error.new is used to construct an instance of NullPointerException. The first main() set up an exception context and then calls demproc(). The demoproc() method then set up another exception_handling context and immediately throws a new instance of NullPointerException, which is caught on the next line. The exception is then rethrown.

throws Exception handling

Throws clause handles the unhandled exception exceptions that are generated by a method. This clause list the types of exceptions that can be thrown by a method.

class ThrowsDemo {
static void throwOne() throws IllegalAcccessException {
System.out.println("Inside throwOne.");
throw new IllegalAcessException("demo");
}
public static void main(String arrgs[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " +e);
}
}
}

output

inside throwOne
caught java.lang.IllegalAccessException:demp

finally Exception handling

Every try block should be associated with at least one catch or finally block. However, it is optional to hava a finally block within a program. If a finally block is included in a program, then it will be executed after the try/catch block but before the code following this try/catch block. The finally block will be executed irrespective of the occurrence of exceptions. A finally block helps in closing opened files, deallocating the allocated memories.

Example program that shows three methods that in various ways, none without executing their finally clause

//Demonstarte finally.
class FinallyDemo {
// Throw an exception out of the method.
static void procA() {
try {
System.out.println("Inside procA");
throw new RunTimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
//Return from within atry block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
//Execute a try block normally.
static void proC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("proC's finally");
}
}
public static void main(String args[] ) {
try {
procA();
} catch (EXception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}

output

inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
10.1 Exception Handling in Java Theory

INSTAGRAM CHANNEL CLICKHERE

TELEGRAM CHANNEL CLICKHERE

Leave a comment