**Exception Handling**
  • An exception is an abnormal condition that arises in a code sequence at run time.

Exception Handling:

  • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

  • Program statements that you want to monitor for exceptions are contained within a try block.

  • If exception occurs it is thrown and then catch will use this exception.

  • System-generated exceptions are automatically thrown by the Java runtime system.

  • To use manually use keyword throw to perform exceptions.

Exception thrown out of method:

  • Any code perform after try block is use keyword finally to execute.

The general form:

try{
// block of code to check error..
}
catch(exception type1){
//exception handler.....
}
finally{
// block of code be executed after try

Exception type:

  • Important subclass of exception is called runtime execption.The runtime exception which defined by
    program are having division by zero and invalid array indexing.

  • Exception handling have another section as error.

  • These error are plotted by java run time execption in run time environment.

Top level exception are

           throwable>        1)exception    2)error

          Execption>        1)runtime eception.
  • In these stack overflow is example of exception handling.

Uncaught exceptions:

  • In these stack trace will always show up the invocation method that cause error.

Example:

public class excep1{
static void subroutine(){
int d=0;
int a=12/d;
}
public static void main (String args[]){
excep1.subroutine();
}
}

Output: java.lang.ArithmeticException: / by zero

at Exc1.subroutine(Exc1.java:4)

at Exc1.main(Exc1.java:7)

Try and catch:

  • try identify and block the code of error

  • catch lets you to handle the error.

  • In these catch is not called and so execution never returns to try block with the catch.so that line is not displayed.

  • Once the catch statement is executed the program control continues in the next line of the program for entire try and catch satement.

Example:

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

Multiple catch class:

  • More than one exception is raised by one single piece of code.

  • Each catch statement is inspected in order and the first one whose type matches that of the exception is executed.

  • After one catch statement is executed it byepassed to other until execution occur upto try and catch block.

Example:

public class MultipleCatches {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
  • When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses.

Nested try statements:

  • Each time a try statement is entered, the context of that exception is pushed on the
    stack.

  • This continues until one of the catch statements succeeds, or until all of the nested try
    statements are exhausted.

Example:

public class MethNestTry {
static void nesttry(int a) {
try {              // nested try block

  //* If one command-line arg is used,then a divide-by-zero exceptionwill 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 exception. \\*
if(a==2) {
int c[] = { 1 };
c[42] = 99;                                     
  // generate an out-of-bounds exception//
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
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-zeroexception. \\*
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

Throw:

  • The general form of throw is shown here:

                                  throw ThrowableInstance;
    
  • Throwable Instance must be an object of type Throwable or a subclass of Throwable.

  • Primitive types, such as int or char, as well as non-Throwable classes such as String and
    Object cannot be used as exceptions.

  • In which Throwable object: using a parameter in a catch clause or creating one with the new operator.

  • If not, then the next enclosing try statement is inspected, and so on.If no matching catch is found,
    then the default exception handler halts the program and prints the stack trace.

Examples:

public 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:

  • In these it throws clause lists the types of exceptions that a method might throw.

  • This is necessary for all exceptions, except those of type Error or RuntimeException or any of their subclasses.

General Form:

type method-name(parameter-list) throws exception-list
{
// body of method
}

Another example:

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

Finally:

  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.

  • The finally keyword is designed to address this contingency.

  • Finally creates a block of code that will be executed after a try /catch block has completed

Example:

public 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 a try 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 procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}

Java’s Built-in Exceptions:

  • Exceptions need not be included in any method’s throws list is called unchecked exceptions.

  • Because the compiler does not check to see if a method handles or throws these exceptions.

  • It included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself.

Own Subclasses in exception:

  • Exception define public constructor.

        1.exception() - no description.
    
         2.exception(string msg) - describe exception.
    

Example:

  • In these parameter greater than 20.it falls to caught exception.otherwise normal exception is used.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
public class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

Output:

Called compute(1)

Normal exit

Called compute(20)

Caught MyException[20]

Chained Exception:

  • Chained Exceptions allows to relate one exception with another exception ( one condition causes to another condition)

  • It has constructors of

    1.throwable( throwable cause)   - where cause is exception that the cause for current exception
    
    2.throwable(string msg, throwable cause) -where msg is the exception msg in where cause is exception 
                                               that the cause for current exception.
    


Example:

public class ExceptionHandling
{
public static void main(String[] args)
{
 try
{
// Creating an exception
NumberFormatException ex = new NumberFormatException("Exception");
// Setting a cause of the exception
ex.initCause(new NullPointerException("This is actual cause of the exception"));
 // Throwing an exception with cause.
throw ex;
}
catch(NumberFormatException ex)
{
// displaying the exception
System.out.println(ex);
// Getting the actual cause of the exception
System.out.println(ex.getCause());
}
}
}

Three recently added exception feature:

  • Here is a catch statement that uses the multi-catch feature to catch both

        ArithmeticException and ArrayIndexOutOfBoundsException:
    

Example:

public class MultiCatch {
public static void main(String args[]) {
int a=10, b=0;
int vals[] = { 1, 2, 3 };
try {
int result = a / b; // generate an ArithmeticException
// vals[10] = 19; // generate an ArrayIndexOutOfBoundsException
// This catch clause catches both exceptions.
} catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
System.out.println("After multi-catch.");
}
}

results matching ""

    No results matching ""