exception handling programs

Upload: sasirekha-perumalvijayan

Post on 03-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Exception Handling Programs

    1/28

    QUESTION1What is the result of attempting to compile and run this code ?

    public class Test {public static void main(String[] args){int j = 0;

    for(; j < 3; j++){if (j==1) break out;System.out.print(j + "\n");}

    out:{System.out.println("bye");}}}

    1. The code will fail to compile.2. The code will run with no out put3. This will run and print 0, 1 , 2 and "bye"4. This will run and print 1 and "bye"

    ANS : 1

    This will fail to compile because the labelledblock does not enclose the break statement.

    QUESTION2

    What is the result of attempting to compile and run this code ?

    class A extends Exception{}class B extends A{}class C extends B{}public class Test {

    static void aMethod() throws C{ throw new C(); }public static void main(String[] args){int x = 10;try { aMethod(); }catch(A e) { System.out.println("Error A");}catch(B e) { System.out.println("Error B");}}

    }

    1. Compiler error2. It will print "Error A"3. It will print "Error B"4. The exception will go uncaught by both catch blocks

    ANS : 1

    This will not compile because B is a subclass of A,so it must come before A. For multiple catch statementsthe rule is to place the the subclass exceptions beforethe superclass exceptions.

    QUESTION3

    Will the print line statement execute here?while(true?true:false)

  • 7/29/2019 Exception Handling Programs

    2/28

    {System.out.println("hello");break;}

    1. Yes2. No

    ANS : 1The boolean condition here evaluates to trueso the print line will execute once.

    QUESTION4

    What is the result of trying to compile and run this?public class Test {public static void main(String[] args){for(int i=0; i < 2; i++){continue;

    System.out.println("Hello world");}

    }}

    1. Prints "Hello world" once2. Prints "Hello world" twice3. Compiler error4. Runs without any output

    ANS : 3

    This will not compile because the print line statementis unreachable.

    QUESTION5

    Consider this code.public class Test {public static void main(String[] args){

    for(int j = 0; j < 1 ; j++){

    if (j < 1) continue innerLoop;innerLoop: for(int i = 0; i < 2; i++)

    {System.out.println("Hello world");}

    }}

    }What is the result of attempting to compile and run this.

    1. The code will not compile.2. It will run and print "Hello world" twice.3. It will run and print "Hello world" once.4. It will run and print "Hello world" thrice.5. It will run with no output

  • 7/29/2019 Exception Handling Programs

    3/28

    ANS : 1

    QUESTION6

    What will the output be ?public static void main(String[] args){char c = '\u0042';switch(c) {default:System.out.println("Default");case 'A':System.out.println("A");case 'B':System.out.println("B");case 'C':System.out.println("C");}}

    1. Prints - Default , A , B , C2. Prints - A3. Prints - B , C4. Prints - A, B , C , Default5. Prints - Default

    ANS : 3

    QUESTION7

    What wil be printed out when this method runs ?void getCount(){int counter = 0;for (int i=10; i>0; i--) {

    int j = 0;while (j > 10) {

    if (j > i) break;counter++;j++;

    }}System.out.println(counter);

    }

    1. 642. 533. 76

    4. 0

    ANS : 4

    Counter never gets incremented because the inner loopis never entered.

    QUESTION8

    Is this code legal ?

  • 7/29/2019 Exception Handling Programs

    4/28

    class ExceptionA extends Exception {}class ExceptionB extends ExceptionA {}public class Test{

    void thrower() throws ExceptionB{throw new ExceptionB();}public static void main(String[] args){Test t = new Test();try{t.thrower();}catch(ExceptionA e) {}catch(ExceptionB e) {}

    }}

    1. Yes2. No

    ANS : 2

    QUESTION9

    Is this legal ?class ExceptionA extends Exception {}class ExceptionB extends ExceptionA {}public class Test{

    void thrower() throws ExceptionA{throw new ExceptionA();

    }public static void main(String[] args){

    Test t = new Test();try{t.thrower();}catch(ExceptionB e) {}

    }}

    1. Yes2. No

    ANS : 2

    correct answer/s : 2

    QUESTION10

    Is this legal ?class ExceptionA extends Exception {}class ExceptionB extends ExceptionA {}

    class A{void thrower() throws ExceptionA{throw new ExceptionA();}

    }public class B extends A{

    void thrower() throws ExceptionB{throw new ExceptionB();

    }}

  • 7/29/2019 Exception Handling Programs

    5/28

    1. Yes2. No

    ANS : 1

    public class ExceptionMethods {

    public static voidmain(String[] args) {

    try {

    throw new Exception("My Exception");

    } catch (Exception e) {

    System.err.println("Caught Exception");

    System.err.println("getMessage():" + e.getMessage());

    System.err.println("getLocalizedMessage():"

    + e.getLocalizedMessage());

    System.err.println("toString():" + e);

    System.err.println("printStackTrace():");

    e.printStackTrace();

    }

    }

    }

    Ignoring RuntimeExceptions

    public class NeverCaught {

    static voidf() {

    throw new RuntimeException("From f()");

    }

    static voidg() {

    f();

    }

    public static voidmain(String[] args) {

    g();

    }

    }

  • 7/29/2019 Exception Handling Programs

    6/28

    Exception in main method

    import java.io.FileInputStream;

    public classMainException {

    // Pass all exceptions to the console:

    public static voidmain(String[] args) throws Exception {

    // Open the file:

    FileInputStream file = new FileInputStream("MainException.java");

    // Use the file ...

    // Close the file:

    file.close();

    }

    }

    1) Which package contains exception handling related classes?

    java.lang

    2) What are the two types of Exceptions?

    Checked Exceptions and Unchecked Exceptions.

    3) What is the base class of all exceptions?

    java.lang.Throwable

    4) What is the difference between Exception and Error in java?

    Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that

    user program should catch. Error defines exceptions that are not excepted to be caught by the user program.

    Example is Stack Overflow

    5) What is the difference between throw and throws?

    Throw is used to explicitly raise a exception within the program, the statement would be throw new Exception();

    throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so

    the callers of the method can guard against the exceptions.

  • 7/29/2019 Exception Handling Programs

    7/28

    Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a

    comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

    6) Differentiate between Checked Exceptions and Unchecked Exceptions?

    Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled

    checked exceptions results in compilation error.

    Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and

    it's subclasses, Error and it's subclasses fall under unchecked exceptions.

    7) What are User defined Exceptions?

    Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by

    extending Exception class.

    What is the importance of finally block in exception handling?

    Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will

    execute even if no catch statement match the exception. Any time a method is about to return to the caller from

    inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed.Finally is used to free up resources like database connections, IO handles, etc.

    9) Can a catch block exist without a try block?

    No. A catch block should always go with a try block.

    10) Can a finally block exist with a try block but without a catch?

    Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

    11) What will happen to the Exception object after exception handling?

    Exception object will be garbage collected.

  • 7/29/2019 Exception Handling Programs

    8/28

    12) The subclass exception should precede the base class exception when used within the catch clause. True/False?

    True.

    13) Exceptions can be caught or rethrown to a calling method. True/False?

    True.

    14) The statements following the throw keyword in a program are not executed. True/False?

    True.

    15) How does finally block differ from finalize() method?

    Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a

    protected method in the Object class which is called by the JVM just before an object is garbage collected.

    16) What are the constraints imposed by overriding on exception handling?

    An overriding method in a subclass may only throw exceptions declared in the parent class or children of the

    exceptions declared in the parent class.

    -----------------------------------------------------------------------------------------------------------------------------------------

    class MyException extends Exception {

    public MyException() {

    }

    public MyException(String msg) {

    super(msg);

    }

    }

    public class FullConstructors {

    public static voidf() throws MyException {

    System.out.println("Throwing MyException from f()");

    throw new MyException();

    }

    public static voidg() throws MyException {

  • 7/29/2019 Exception Handling Programs

    9/28

    System.out.println("Throwing MyException from g()");

    throw new MyException("Originated in g()");

    }

    public static voidmain(String[] args) {

    try {

    f();

    } catch (MyException e) {

    e.printStackTrace();

    }

    try {

    g();

    } catch (MyException e) {

    e.printStackTrace();

    }

    }

    }

    Illustrate various Exceptions

    import java.util.Date;

    import java.util.EmptyStackException;

    import java.util.Stack;

    public class ExceptionalTest {

    public static voidmain(String[] args) {

    int count = 1000000;

    Stack s = new Stack();

    System.out.println("Testing for empty stack");

    long s1 = System.currentTimeMillis();

    for (int i = 0; i

  • 7/29/2019 Exception Handling Programs

    10/28

    /** Simple demo of exceptions */

    public class ExceptionDemo {

    public static voidmain(String[] argv) {

    new ExceptionDemo().doTheWork();

    }

    /** This method demonstrates calling a method that might throw

    * an exception, and catching the resulting exception.

    */

    public voiddoTheWork() {

    Object o = null;

    for (int i=0; i

  • 7/29/2019 Exception Handling Programs

    11/28

    throw new RuntimeException(e);

    }

    }

    }

    class SomeOtherException extends Exception {}

    public class TurnOffChecking {

    public static voidmain(String[] args) {

    WrapCheckedException wce = new WrapCheckedException();

    // You can call f() without a try block, and let

    // RuntimeExceptions go out of the method:

    wce.throwRuntimeException(3);

    // Or you can choose to catch exceptions:

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

    try {

    if(i < 3)

    wce.throwRuntimeException(i);

    else

    throw new SomeOtherException();

    } catch(SomeOtherException e) {

    System.out.println("SomeOtherException: " + e);

    } catch(RuntimeException re) {

    try {

    throw re.getCause(); } catch(FileNotFoundException e) {

    System.out.println(

    "FileNotFoundException: " + e);

    } catch(IOException e) {

    System.out.println("IOException: " + e);

    } catch(Throwable e) {

    System.out.println("Throwable: " + e);

    }

    }

    }

    }

    Question 1

    class A {public static void main (String[] args) {Error error = new Error();Exception exception = new Exception();System.out.print((exception instanceof Throwable) + ",");

  • 7/29/2019 Exception Handling Programs

    12/28

    System.out.print(error instanceof Throwable);}}

    What is the result of attempting to compile and run the program?

    a. Prints: false,falseb. Prints: false,true

    c. Prints: true,false

    d. Prints: true,true

    e. Compile-time error

    f. Run-time error

    g. None of the above

    Question 2

    class A {A() throws Exception {}} // 1class B extends A {B() throws Exception {}} // 2class C extends A {C() {}} // 3

    Which of the following statements are true?

    a. class A extends Object.

    b. Compile-time error at 1.

    c. Compile-time error at 2.

    d. Compile-time error at 3.

    Question 3

    class A {public static void main (String[] args) {Object error = new Error();Object runtimeException = new RuntimeException();System.out.print((error instanceof Exception) + ",");System.out.print(runtimeException instanceof Exception);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: false,false

    b. Prints: false,true

    c. Prints: true,false

    d. Prints: true,true

    e. Compile-time error

    f. Run-time error

    g. None of the above

  • 7/29/2019 Exception Handling Programs

    13/28

    Question 4

    class Level1Exception extends Exception {}class Level2Exception extends Level1Exception {}

    class Level3Exception extends Level2Exception {}class Purple {public static void main(String args[]) {int a,b,c,d,f,g,x;a = b = c = d = f = g = 0;x = 1;try {try {switch (x) {case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();

    } a++; }catch (Level2Exception e) {b++;}finally {c++;}

    }catch (Level1Exception e) { d++;}catch (Exception e) {f++;}finally {g++;}System.out.print(a+","+b+","+c+","+d+","+f+","+g);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,0,0,1,0,0

    b. Prints: 0,0,1,1,0,1

    c. Prints: 0,1,1,1,0,1

    d. Prints: 1,0,1,1,0,1

    e. Prints: 1,1,1,1,0,1

    f. Compile-time error

    g. Run-time error

    h. None of the above

    Question 5

    class Level1Exception extends Exception {}class Level2Exception extends Level1Exception {}class Level3Exception extends Level2Exception {}class Purple {public static void main(String args[]) {int a,b,c,d,f,g,x;a = b = c = d = f = g = 0;x = 2;try {try {

  • 7/29/2019 Exception Handling Programs

    14/28

    switch (x) {case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();

    } a++; }catch (Level2Exception e) {b++;}finally {c++;}

    }catch (Level1Exception e) { d++;}catch (Exception e) {f++;}finally {g++;}System.out.print(a+","+b+","+c+","+d+","+f+","+g);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,0,1,0,0,1

    b. Prints: 0,1,0,0,0,0

    c. Prints: 0,1,1,0,0,1d. Prints: 0,1,0,0,0,1

    e. Prints: 1,1,1,0,0,1

    f. Compile-time error

    g. Run-time error

    h. None of the above

    Question 6

    class Level1Exception extends Exception {}

    class Level2Exception extends Level1Exception {}class Level3Exception extends Level2Exception {}class Purple {public static void main(String args[]) {int a,b,c,d,f,g,x;a = b = c = d = f = g = 0;x = 3;try {try {switch (x) {case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();

    } a++; }

    catch (Level2Exception e) {b++;}finally {c++;}

    }catch (Level1Exception e) { d++;}catch (Exception e) {f++;}finally {g++;}System.out.print(a+","+b+","+c+","+d+","+f+","+g);

    }}

  • 7/29/2019 Exception Handling Programs

    15/28

    What is the result of attempting to compile and run the program?

    a. Prints: 1,1,1,0,0,1

    b. Prints: 0,1,1,0,0,1

    c. Prints: 0,1,0,0,0,0

    d. Prints: 0,1,0,0,0,1

    e. Prints: 0,0,1,0,0,1

    f. Compile-time error

    g. Run-time error

    h. None of the above

    Question 7

    class Level1Exception extends Exception {}class Level2Exception extends Level1Exception {}

    class Level3Exception extends Level2Exception {}class Purple {public static void main(String args[]) {int a,b,c,d,f,g,x;a = b = c = d = f = g = 0;x = 4;try {try {switch (x) {

    case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();case 4: throw new Exception();

    } a++; }catch (Level2Exception e) {b++;}finally{c++;}

    }catch (Level1Exception e) { d++;}catch (Exception e) {f++;}finally {g++;}System.out.print(a+","+b+","+c+","+d+","+f+","+g);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,0,0,0,0,1

    b. Prints: 0,0,0,0,1,0

    c. Prints: 0,0,1,0,0,1

    d. Prints: 0,0,1,0,1,1

    e. Prints: 0,1,1,1,1,1

    f. Prints: 1,1,1,1,1,1

    g. Compile-time error

    h. Run-time error

  • 7/29/2019 Exception Handling Programs

    16/28

    i. None of the above

    Question 8

    class Level1Exception extends Exception {}

    class Level2Exception extends Level1Exception {}class Level3Exception extends Level2Exception {}class Purple {public static void main(String args[]) {int a,b,c,d,f,g,x;a = b = c = d = f = g = 0;x = 5;try {try {switch (x) {

    case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();

    case 4: throw new Exception();} a++; }catch (Level2Exception e) {b++;}finally {c++;}

    }catch (Level1Exception e) { d++;}catch (Exception e) {f++;}finally {g++;}System.out.print(a+","+b+","+c+","+d+","+f+","+g);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 1,0,0,0,0,0

    b. Prints: 1,0,1,0,0,1

    c. Prints: 0,0,1,0,0,1

    d. Prints: 1,1,1,1,1,1

    e. Compile-time error

    f. Run-time error

    g. None of the above

    Question 9

    class ColorException extends Exception {}class WhiteException extends ColorException {}class White {void m1() throws ColorException {throw new WhiteException();}void m2() throws WhiteException {}public static void main (String[] args) {White white = new White();int a,b,d,f; a = b = d = f = 0;try {white.m1(); a++;} catch (ColorException e) {b++;}

  • 7/29/2019 Exception Handling Programs

    17/28

    try {white.m2(); d++;} catch (WhiteException e) {f++;}System.out.print(a+","+b+","+d+","+f);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,1,0,0

    b. Prints: 1,1,0,0

    c. Prints: 0,1,1,0

    d. Prints: 1,1,1,0

    e. Prints: 1,1,1,1

    f. Compile-time error

    g. Run-time error

    h. None of the above

    Question 10class ColorException extends Exception {}class WhiteException extends ColorException {}class White {void m1() throws ColorException {throw new ColorException();}void m2() throws WhiteException {throw new ColorException();}public static void main (String[] args) {White white = new White();int a,b,d,f; a = b = d = f = 0;try {white.m1(); a++;} catch (ColorException e) {b++;}try {white.m2(); d++;} catch (WhiteException e) {f++;}System.out.print(a+","+b+","+d+","+f);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,1,0,0

    b. Prints: 1,1,0,1

    c. Prints: 0,1,0,1

    d. Prints: 0,1,1,1

    e. Prints: 1,1,1,1

    f. Compile-time error

    g. Run-time errorh. None of the above

    Question 11

    class ColorException extends Exception {}class WhiteException extends ColorException {}class White {

  • 7/29/2019 Exception Handling Programs

    18/28

    void m1() throws ColorException {throw new ColorException();}void m2() throws WhiteException {throw new WhiteException();}public static void main (String[] args) {White white = new White();int a,b,d,f; a = b = d = f = 0;try {white.m1(); a++;} catch (WhiteException e) {b++;}try {white.m2(); d++;} catch (WhiteException e) {f++;}System.out.print(a+","+b+","+d+","+f);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,1,0,0

    b. Prints: 1,1,0,1

    c. Prints: 0,1,0,1

    d. Prints: 0,1,1,1

    e. Prints: 1,1,1,1

    f. Compile-time errorg. Run-time error

    h. None of the above

    Question 12

    class Level1Exception extends Exception {}class Level2Exception extends Level1Exception {}class Level3Exception extends Level2Exception {}class Brown {public static void main(String args[]) {

    int a, b, c, d, f; a = b = c = d = f = 0;int x = 1;try {switch (x) {case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();

    } a++; }catch (Level3Exception e) {b++;}catch (Level2Exception e) {c++;}catch (Level1Exception e) {d++;}finally {f++;}System.out.print(a+","+b+","+c+","+d+","+f);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,0,0,1,1

    b. Prints: 0,0,1,1,1

    c. Prints: 0,1,1,1,1

    d. Prints: 1,1,1,1,1

  • 7/29/2019 Exception Handling Programs

    19/28

    e. Prints: 0,0,1,0,1

    f. Prints: 0,1,0,0,1

    g. Prints: 1,0,0,0,1

    h. Compile-time error

    i. Run-time error

    j. None of the above

    Question 13

    class Level1Exception extends Exception {}class Level2Exception extends Level1Exception {}class Level3Exception extends Level2Exception {}class Brown {public static void main(String args[]) {int a, b, c, d, f; a = b = c = d = f = 0;int x = 2;try {switch (x) {case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();

    } a++; }catch (Level3Exception e) {b++;}catch (Level2Exception e) {c++;}catch (Level1Exception e) {d++;}finally {f++;}System.out.print(a+","+b+","+c+","+d+","+f);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,0,0,1,1

    b. Prints: 0,0,1,1,1

    c. Prints: 0,1,1,1,1

    d. Prints: 1,1,1,1,1

    e. Prints: 0,0,1,0,1

    f. Prints: 0,1,0,0,1

    g. Prints: 1,0,0,0,1

    h. Compile-time error

    i. Run-time errorj. None of the above

    Question 14

    class Level1Exception extends Exception {}class Level2Exception extends Level1Exception {}class Level3Exception extends Level2Exception {}

  • 7/29/2019 Exception Handling Programs

    20/28

    class Brown {public static void main(String args[]) {int a, b, c, d, f; a = b = c = d = f = 0;int x = 4;try {switch (x) {case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();

    } a++; }catch (Level3Exception e) {b++;}catch (Level2Exception e) {c++;}catch (Level1Exception e) {d++;}finally {f++;}System.out.print(a+","+b+","+c+","+d+","+f);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,0,0,1,1b. Prints: 0,0,1,1,1

    c. Prints: 0,1,1,1,1

    d. Prints: 1,1,1,1,1

    e. Prints: 0,0,1,0,1

    f. Prints: 0,1,0,0,1

    g. Prints: 1,0,0,0,1

    h. Compile-time error

    i. Run-time error

    j. None of the above

    Question 15

    class ColorException extends Exception {}class WhiteException extends ColorException {}abstract class Color {abstract void m1() throws ColorException;

    }class White extends Color {void m1() throws WhiteException {throw new WhiteException();}public static void main (String[] args) {White white = new White();

    int a,b,c; a = b = c = 0;try {white.m1(); a++;}catch (WhiteException e) {b++;}finally {c++;}

    System.out.print(a+","+b+","+c);}}

    What is the result of attempting to compile and run the program?

  • 7/29/2019 Exception Handling Programs

    21/28

    a. Prints: 0,0,0

    b. Prints: 0,0,1

    c. Prints: 0,1,0

    d. Prints: 0,1,1

    e. Prints: 1,0,0

    f. Prints: 1,0,1

    g. Prints: 1,1,0

    h. Prints: 1,1,1

    i. Compile-time error

    j. Run-time error

    k. None of the above

    Question 16

    class RedException extends Exception {}

    class BlueException extends Exception {}class White {void m1() throws RedException {throw new RedException();}public static void main (String[] args) {White white = new White();int a,b,c,d; a = b = c = d = 0;try {white.m1(); a++;}catch (RedException e) {b++;}catch (BlueException e) {c++;}finally {d++;}

    System.out.print(a+","+b+","+c+","+d);}}

    What is the result of attempting to compile and run the program?

    a. Prints: 0,1,0,0

    b. Prints: 1,1,0,1

    c. Prints: 0,1,0,1

    d. Prints: 0,1,1,1

    e. Prints: 1,1,1,1

    f. Compile-time error

    g. Run-time error

    h. None of the above

    Question 17

    class Level1Exception extends Exception {}class Level2Exception extends Level1Exception {}class Level3Exception extends Level2Exception {}class Purple {public static void main(String args[]) {

  • 7/29/2019 Exception Handling Programs

    22/28

    int a,b,c,d,f,g,x;a = b = c = d = f = g = 0;x = 1;try {throw new Level1Exception();try {switch (x) {case 1: throw new Level1Exception();case 2: throw new Level2Exception();case 3: throw new Level3Exception();

    } a++; }catch (Level2Exception e) {b++;}finally {c++;}

    }catch (Level1Exception e) { d++;}catch (Exception e) {f++;}finally {g++;}System.out.print(a+","+b+","+c+","+d+","+f+","+g);

    }}

    What is the result of attempting to compile and run the program?

    a. Prints: 1,1,1,0,0,1

    b. Prints: 0,1,1,0,0,1

    c. Prints: 0,1,0,0,0,0

    d. Prints: 0,1,0,0,0,1

    e. Prints: 0,0,1,0,0,1

    f. Compile-time error

    g. Run-time error

    h. None of the above

    Answers:

    No. Answer Remark

    1 d Prints: true,true Both Errorand Exare subclasses ofTh.

    2a

    d

    class A extendsObject.

    Compile-time

    error at 3.

    The constructors for class Band class Cboth invoke the constructor forA.The constructor for class Adeclares Exceptionin the throwsclause. Since the constructors

    forBand Cinvoke the constructor forA, it is necessary to declare Exin the thro

    clauses ofBand C. A compile-time error is generated at marker 3, because

    the constructor does not declare Exin the throclause.3 b Prints: false,true Errois a direct subclass ofTh. Runtim eEis a direct subclass ofEx.

    4 bPrints:

    0,0,1,1,0,1

    The nested catcclause is able to catch a Level2 Exor any subclass of it. The switchstatement

    throws a Level1 Exthat can not be caught by the nested catchclause; so the nested f

    block is executed as control passes to the first of the two outercatcclauses.The outerfblock is executed as control passes out of the trystatement.

    5 c Prints: The nested catchblock is able to catch a Level2 Exor any subclass of it causing bto be

  • 7/29/2019 Exception Handling Programs

    23/28

    No. Answer Remark

    0,1,1,0,0,1 incremented. Both of the finablocks are then executed.

    6 bPrints:

    0,1,1,0,0,1

    The nested catchblock is able to catch a Leor any subclass of it causing bto be

    incremented. Both of the finablocks are then executed.

    7 dPrints:

    0,0,1,0,1,1

    The nested catchclause is able to catch a Leor any subclass of it. The switstatementthrows an Exceptionthat can not be caught by the nested catchclause; so the nested fina

    block is executed as control passes to the second of the two outercatch

    clauses. The outerfinallblock is executed as control passes out of the try

    statement.

    8

    bPrints:

    1,0,1,0,0,1

    The switstatement does not throw an exception; so the switcompletes normally.

    The subsequent statement increments the variable, a; and the tryblock

    completes normally. Both of the finablocks are then executed.

    9 c Prints: 0,1,1,0

    The first tryblock contains two statements. The first invokes method m, andthe subsequent statement contains a post increment expression with the

    variable, a, as the operand. Method m 1throws a WhiteExceptiexception, so variable ais

    not incremented as control passes to the catcblock where bis incremented.The throwsclause ofm 1declares a ColorException, so the body may throw a ColorExceptionor any subclass ofColorE.

    The second tryblock also contains two statements. The first invokes

    method m 2, and the subsequent statement contains a post increment

    expression with the variable, d, as the operand. Method m does not throwan exception, so dis incremented, and the tryblock completes normally.

    Although the throclause ofm 2declares a WhiteException, there is no requirement to throw any

    exception.

    10f

    Compile-time

    error

    The throclause ofWhitdeclares a WhiteException, so the body ofm2may throw a WhiteExceptionor any subclassofWhiteException. Instead, the body ofm2throws a superclass ofWhiteException. The result is a compile-

    time error.

    11 fCompile-time

    error

    The throclause ofWhdeclares a ColorException, but the c aclause in the mainmethod catches only a

    subclass ofColorException. The result is a compile-time error.

    12 a Prints: 0,0,0,1,1 The first catchclause has a parametereof type Level3 Ex, so the first catchclause is able to

    catch any exception type that is assignable to type Level3 Ex. Since Level2Exceptiois the

    superclass ofLevel3 Ex, an instance ofLevel2Exceptionis not assignable to a catcclause parameter of

    type Level3 Ex. Similarly, Level1Exceptionis also a superclass ofLevel3Exception, so an instance ofLevel1Exceptiois notassignable to a catcclause parameter of type Level3 Ex. The only exception type that

    can be caught by the first catchclause is a Level3 Ex. The second catchclause has a

    parametereof type Level2 Ex, so the second catcclause is able to catch a Level2. The Level1Exceis thesuperclass ofLe v el2. An instance ofLevel1Exceptionis not assignable to a catcclause parameter of

    type Le v el2 io, so the second catcclause can not catch a Le v 1. Since a Level3Exceptionis a subclass ofLevel2Excepanexception of type Level3Exceptionis assignable to a catchclause parameter type Le. Allexceptions of type Level3will be caught by the first catchclause, so the second catch

    clause in this program will not have an opportunity to catch a Le. The thirdcatcclause has a parametereof type L e, so the third catcclause is able to catch a L.The exceptions of type L eand Level3Exceptionare assignable to the catcclause parameter of

    the third catch clause, but the exceptions of those subclass types will be

    caught by the first two catchclauses. The switchstatement throws a L . The tryblock

  • 7/29/2019 Exception Handling Programs

    24/28

    No. Answer Remark

    completes abruptly as control passes to the third catcblock where dis

    incremented. The finablock is also executed, so fis incremented.

    13 e Prints: 0,0,1,0,1

    The first catchblock is able to catch a Leor any subclass ofLevel3Exception. The second catchblockis able to catch a Leor any subclass ofLevel2Exception. The switstatement throws a Le. The try

    block completes abruptly as control passes to the second catcblock where c

    is incremented. The finablock is also executed, so fis incremented.

    14g Prints: 1,0,0,0,1 The switstatement does not throw an exception; so the switchcompletes normally.

    The subsequent statement increments the variable, a; and the tryblock

    completes normally. The finablock is also executed, so fis incremented.

    15 d Prints: 0,1,1

    The tryblock contains two statements. The first invokes method m1, and the

    subsequent statement contains a post increment expression with thevariable, a, as the operand. Method m1throws a WhiteExceptionexception, so variable ais

    not incremented as control passes to the catchblock where bis incremented.

    Although Colodeclares a ColorExceptionin the throwsclause, a subclass ofColois free to declare only

    a subclass ofColorExceptionin the throwsclause of the overriding method.

    16 fCompile-time

    error

    A compile-time error is generated, because the second catchclause attempts

    to catch an exception that is never thrown in the tryblock.

    17 fCompile-timeerror

    A throwstatement is the first statement in the outertryblock. A throwstatement

    appearing in a tryblock causes control to pass out of the block.Consequently, statements can not be reached if they appear in the block

    after the throstatement. The switchstatement that appears after the throwstatement is

    unreachable and results in a compile-time error.

    1) What is an Exception?

    An exception is an abnormal condition that arises in a code sequence at run time. In otherwords, an exception is a run-time error.

    2) What is a Java Exception?

    A Java exception is an object that describes an exceptional condition i.e., an error conditionthat has occurred in a piece of code. When this type of condition arises, an object

    representing that exception is created and thrown in the method that caused the error bythe Java Runtime. That method may choose to handle the exception itself, or pass it on.

    Either way, at some point, the exception is caught and processed.

    3) What are the different ways to generate

    and Exception?

    There are two different ways to generate an Exception.

  • 7/29/2019 Exception Handling Programs

    25/28

    1. Exceptions can be generated by the Java run-time system.

    Exceptions thrown by Java relate to fundamental errors that violate the rules of theJava language or the constraints of the Java execution environment.

    2. Exceptions can be manually generated by your code.

    Manually generated exceptions are typically used to report some error condition tothe caller of a method.

    4) Where does Exception stand in the Javatree hierarchy?

    java.lang.Object

    java.lang.Throwable

    java.lang.Exception

    java.lang.Error

    5) Is it compulsory to use the finally block?

    It is always a good practice to use the finally block. The reason for using the finally block is,any unreleased resources can be released and the memory can be freed. For example while

    closing a connection object an exception has occurred. In finally block we can close thatobject. Coming to the question, you can omit the finally block when there is a catch block

    associated with that try block. A try block should have at least a catch or a finally block.

    6) How are try, catch and finally block

    organized?

    A try block should associate with at least a catch or a finally block. The sequence of try,

    catch and finally matters a lot. If you modify the order of these then the code wontcompile. Adding to this there can be multiple catch blocks associated with a try block. The

    final concept is there should be a single try, multiple catch blocks and a single finally blockin a try-catch-finally block.

    7) What is a throw in an Exception block?

    throw is used to manually throw an exception (object) of type Throwable class or asubclass ofThrowable. Simple types, such as int or char, as well as non-Throwable

    classes, such as String and Object, cannot be used as exceptions. The flow of executionstops immediately after the throw statement; any subsequent statements are not

    executed.

    throwThrowableInstance;

  • 7/29/2019 Exception Handling Programs

    26/28

    ThrowableInstance must be an object of type Throwable or a subclass ofThrowable.

    throw new NullPointerException("thrownException");

    8) What is the use of throws keyword?If a method is capable of causing an exception that it does not handle, it must specify this

    behavior so that callers of the method can guard themselves against that exception. You do

    this by including a throws clause in the methods declaration. A throws clause lists thetypes of exceptions that a method might throw.

    type method-name(parameter-list)throwsexception-list{

    // body of method}

    Warning:

    main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html):failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in/home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-

    1.html on line 195

    Warning:

    main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html):failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in/home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-

    1.html on line 195

    Warning: main(): Failed opening'http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html' forinclusion

    (include_path='.:/usr/local/lib/php') in/home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html

    on line 195

    Here, exception-list is a comma-separated list of the exceptions thata method can throw.

    static void throwOne() throws IllegalAccessException {

    System.out.println("Inside throwOne.");

    9) What are Checked Exceptions and

    Unchecked Exceptions?

    The types of exceptions that need not be included in a methods throws list are called

    Unchecked Exceptions.

    ArithmeticException

  • 7/29/2019 Exception Handling Programs

    27/28

    ArrayIndexOutOfBoundsException

    ClassCastException

    IndexOutOfBoundsException

    IllegalStateException

    NullPointerException

    SecurityException

    The types of exceptions that must be included in a methods throws list if that method cangenerate one of these exceptions and does not handle it itself are called Checked

    Exceptions.

    ClassNotFoundException

    CloneNotSupportedException

    IllegalAccessException

    InstantiationException

    InterruptedException

    NoSuchFieldException

    NoSuchMethodException

    10) What are Chained Exceptions?

    The chained exception feature allows you to associate another exception with an exception.

    This second exception describes the cause of the first exception. Lets take a simple

    example. You are trying to read a number from the disk and using it to divide a number.Think the method throws an ArithmeticException because of an attempt to divide by zero

    (number we got). However, the problem was that an I/O error occurred, which caused thedivisor to be set improperly (set to zero). Although the method must certainly throw an

    ArithmeticException, since that is the error that occurred, you might also want to let thecalling code know that the underlying cause was an I/O error. This is the place where

    chained exceptions come in to picture.

    Throwable getCause( )

    Throwable initCause(Throwable causeExc)

    Stopping a a thread using Thread.interrrut method

    class Example1 extends Thread {

    public static void main( String args[] ) throws Exception {

    Example1 thread = new Example1();

    System.out.println( "Starting thread..." );

    thread.start();

    Thread.sleep( 3000 );

    System.out.println( "Interrupting thread..." );

  • 7/29/2019 Exception Handling Programs

    28/28

    thread.interrupt();

    Thread.sleep( 3000 );

    System.out.println( "Stopping application..." );

    System.exit( 0 );

    }

    public void run() {

    while ( true ) {

    System.out.println( "Thread is running..." );

    long time = System.currentTimeMillis();

    while ( System.currentTimeMillis()-time < 1000 ) {

    }

    }

    }

    }