You are on page 1of 28

QUESTION1 What 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. 2. 3. 4. The code will The code will This will run This will run fail to compile. run with no out put and print 0, 1 , 2 and "bye" and print 1 and "bye"

ANS : 1 This will fail to compile because the labelled block 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. 2. 3. 4. Compiler error It will print "Error A" It will print "Error B" 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 statements the rule is to place the the subclass exceptions before the superclass exceptions. QUESTION3 Will the print line statement execute here? while(true?true:false)

{ } 1. Yes 2. No

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

ANS : 1 The boolean condition here evaluates to true so 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. 2. 3. 4. Prints "Hello world" once Prints "Hello world" twice Compiler error Runs without any output

ANS : 3 This will not compile because the print line statement is 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. 2. 3. 4. 5. The code will not compile. It will run and print "Hello world" twice. It will run and print "Hello world" once. It will run and print "Hello world" thrice. It will run with no output

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. 2. 3. 4. 5. Prints Prints Prints Prints Prints Default , A , B , C A B , C A, B , C , Default 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. 2. 3. 4. 64 53 76 0

ANS : 4 Counter never gets incremented because the inner loop is never entered. QUESTION8 Is this code legal ?

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. Yes 2. 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. Yes 2. 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(); } }

1. Yes 2. No ANS : 1 public class ExceptionMethods { public static void main(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 void f() { throw new RuntimeException("From f()"); } static void g() { f(); } public static void main(String[] args) { g(); } }

Exception in main method


import java.io.FileInputStream; public class MainException { // Pass all exceptions to the console: public static void main(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.

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.

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 void f() throws MyException { System.out.println("Throwing MyException from f()"); throw new MyException(); } public static void g() throws MyException {

System.out.println("Throwing MyException from g()"); throw new MyException("Originated in g()"); } public static void main(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 void main(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 <= count; i++) if (!s.empty()) s.pop(); long s2 = System.currentTimeMillis(); System.out.println((s2 - s1) + " milliseconds"); System.out.println("Catching EmptyStackException"); s1 = System.currentTimeMillis(); for (int i = 0; i <= count; i++) { try { s.pop(); } catch (EmptyStackException e) { } } s2 = System.currentTimeMillis(); System.out.println((s2 - s1) + " milliseconds"); } }

/** Simple demo of exceptions */ public class ExceptionDemo { public static void main(String[] argv) { new ExceptionDemo().doTheWork(); } /** This method demonstrates calling a method that might throw * an exception, and catching the resulting exception. */ public void doTheWork() { Object o = null; for (int i=0; i<5; i++) { try { o = makeObj(i); } catch (IllegalArgumentException e) { System.err.println("Error: (" + e.getMessage() + ")."); return; // cut off println below if makeObj failed. } System.out.println(o); // process the created object in some way } } /** Model of a method that creates and returns an object. * This method is really here to show how you throw exceptions. * @exception IllegalArgumentException if called with value 1. */ public Object makeObj(int type) throws IllegalArgumentException { if (type == 1) // detects an error... throw new IllegalArgumentException("Don't like type " + type); return new Object(); } }

Turning off Checked exceptions


import java.io.*; class WrapCheckedException { void throwRuntimeException(int type) { try { switch(type) { case 0: throw new FileNotFoundException(); case 1: throw new IOException(); case 2: throw new RuntimeException("Where am I?"); default: return; } } catch(Exception e) { // Adapt to unchecked:

throw new RuntimeException(e); } } } class SomeOtherException extends Exception {} public class TurnOffChecking { public static void main(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) + ",");

}}

System.out.print(error instanceof Throwable);

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


a. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

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

Which of the following statements are true?


a. b. c. d. class A extends Object. Compile-time error at 1. Compile-time error at 2. 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. b. c. d. e. f. g. Prints: false,false Prints: false,true Prints: true,false Prints: true,true Compile-time error Run-time error None of the above

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. b. c. d. e. f. g. h. Prints: 0,0,0,1,0,0 Prints: 0,0,1,1,0,1 Prints: 0,1,1,1,0,1 Prints: 1,0,1,1,0,1 Prints: 1,1,1,1,0,1 Compile-time error Run-time error 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 {

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

switch (x) { case 1: throw new Level1Exception(); case 2: throw new Level2Exception(); case 3: throw new Level3Exception(); } a++; } catch (Level2Exception e) {b++;} finally {c++;}

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


a. b. c. d. e. f. g. h. Prints: 0,0,1,0,0,1 Prints: 0,1,0,0,0,0 Prints: 0,1,1,0,0,1 Prints: 0,1,0,0,0,1 Prints: 1,1,1,0,0,1 Compile-time error Run-time error 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); }}

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


a. b. c. d. e. f. g. h. Prints: 1,1,1,0,0,1 Prints: 0,1,1,0,0,1 Prints: 0,1,0,0,0,0 Prints: 0,1,0,0,0,1 Prints: 0,0,1,0,0,1 Compile-time error Run-time error 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. b. c. d. e. f. g. h. Prints: 0,0,0,0,0,1 Prints: 0,0,0,0,1,0 Prints: 0,0,1,0,0,1 Prints: 0,0,1,0,1,1 Prints: 0,1,1,1,1,1 Prints: 1,1,1,1,1,1 Compile-time error Run-time error

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. b. c. d. e. f. g. Prints: 1,0,0,0,0,0 Prints: 1,0,1,0,0,1 Prints: 0,0,1,0,0,1 Prints: 1,1,1,1,1,1 Compile-time error Run-time error 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++;}

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. b. c. d. e. f. g. h. Prints: 0,1,0,0 Prints: 1,1,0,0 Prints: 0,1,1,0 Prints: 1,1,1,0 Prints: 1,1,1,1 Compile-time error Run-time error None of the above

Question 10
class 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. b. c. d. e. f. g. h. Prints: 0,1,0,0 Prints: 1,1,0,1 Prints: 0,1,0,1 Prints: 0,1,1,1 Prints: 1,1,1,1 Compile-time error Run-time error None of the above

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

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. b. c. d. e. f. g. h. Prints: 0,1,0,0 Prints: 1,1,0,1 Prints: 0,1,0,1 Prints: 0,1,1,1 Prints: 1,1,1,1 Compile-time error Run-time error 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. b. c. d. Prints: 0,0,0,1,1 Prints: 0,0,1,1,1 Prints: 0,1,1,1,1 Prints: 1,1,1,1,1

e. f. g. h. i. j.

Prints: 0,0,1,0,1 Prints: 0,1,0,0,1 Prints: 1,0,0,0,1 Compile-time error Run-time error 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. b. c. d. e. f. g. h. i. j. Prints: 0,0,0,1,1 Prints: 0,0,1,1,1 Prints: 0,1,1,1,1 Prints: 1,1,1,1,1 Prints: 0,0,1,0,1 Prints: 0,1,0,0,1 Prints: 1,0,0,0,1 Compile-time error Run-time error None of the above

Question 14
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 = 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. b. c. d. e. f. g. h. i. j. Prints: 0,0,0,1,1 Prints: 0,0,1,1,1 Prints: 0,1,1,1,1 Prints: 1,1,1,1,1 Prints: 0,0,1,0,1 Prints: 0,1,0,0,1 Prints: 1,0,0,0,1 Compile-time error Run-time error 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?

a. b. c. d. e. f. g. h. i. j. k.

Prints: 0,0,0 Prints: 0,0,1 Prints: 0,1,0 Prints: 0,1,1 Prints: 1,0,0 Prints: 1,0,1 Prints: 1,1,0 Prints: 1,1,1 Compile-time error Run-time error 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. b. c. d. e. f. g. h. Prints: 0,1,0,0 Prints: 1,1,0,1 Prints: 0,1,0,1 Prints: 0,1,1,1 Prints: 1,1,1,1 Compile-time error Run-time error 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[]) {

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. b. c. d. e. f. g. h. Prints: 1,1,1,0,0,1 Prints: 0,1,1,0,0,1 Prints: 0,1,0,0,0,0 Prints: 0,1,0,0,0,1 Prints: 0,0,1,0,0,1 Compile-time error Run-time error None of the above

Answers:

No. Answer 1 d Prints: true,true

Remark

Both E and r r o rE are x subclasses of . T h The constructors for class B and class C both invoke the constructor for A . class A extends The constructor for class A declares Exception in the t clause. h r o w s Since the constructors a Object. 2 for B and C invoke the constructor for A , it is necessary to declare E in x the t h r o d Compile-time clauses of B and C . A compile-time error is generated at marker 3, because error at 3. the constructor does not declare E in x the t clause. h r o 3 b Prints: false,true E is r r oa direct subclass of . T h R is u n t i m a direct subclass E e of . E x The nested c clause a t c is able to catch a L or e v e l 2 any x subclass E of it. The s statement w i t c h Prints: throws a L that e v e l 1 can not be x caught E by the nested c clause; a t c h so the nested f 4 b 0,0,1,1,0,1 block is executed as control passes to the first of the two outer c clauses. a t c The outer f block is executed as control passes out of the t statement. r y 5 c Prints: The nested c block a t c h is able to catch a L or e v e l 2 any subclass x E of it causing b to be

No.

Answer 0,1,1,0,0,1 Prints: 6 b 0,1,1,0,0,1

7 d

b 8

9 c

f 10 11 f 12 a

Remark incremented. Both of the f blocks i n a are then executed. The nested c block a t c h is able to catch a Le or any subclass of it causing b to be incremented. Both of the f blocks i n a are then executed. The nested c clause a t c h is able to catch a L or e any subclass of it. The s statement w i t throws an Exception that can not be caught by the nested ca clause; t c h so the nested f i n a Prints: block is executed as control passes to the second of the two outer c a t c h 0,0,1,0,1,1 clauses. The outer f block i n a l is executed as control passes out of the t r y statement. The s statement w i t does not throw an exception; so the s completes w i t normally. Prints: The subsequent statement increments the variable, a ; and the t block r y 1,0,1,0,0,1 completes normally. Both of the f blocks i n a are then executed. The first t block r y contains two statements. The first invokes method m , and the subsequent statement contains a post increment expression with the variable, a , as the operand. Method m throws a W exception, h i t e E x c i t p e so variable 1 a is not incremented as control passes to the c block a t c where b is incremented. The t clause h r o w s of m declares a , ColorExceptio so the body n may 1 throw a ColorExcepti or any subclass n o of . ColorExcept n i o Prints: 0,1,1,0 The second try block also contains two statements. The first invokes method , mand the subsequent statement 2 contains a post increment expression with the variable, d , as the operand. Method m does not throw 2 an exception, so d is incremented, and the t block r y completes normally. Although the t clause h r o of m declares a , WhiteExcepti there is no nrequirement o 2 to throw any exception. The t clause h r o of W declares h i t a, WhiteExcepti so the body n of o m2 may throw a WhiteExcepti or any subclass n o Compile-time of . WhiteExcepti Instead, the n body o of m2 throws a superclass of . WhiteExcept The resultn is i o a compileerror time error. Compile-time The t clause h r o of W declares h a, ColorExcept but the c clause n o i in the main method catches aonly a error subclass of . ColorExcept The result n is a o icompile-time error. Prints: 0,0,0,1,1 The first c clause a t c h has a parameter e of type , L e so v e l 3thex first E c clause a t c h is able to catch any exception type that is assignable to type . L e Since v e l 3 Level2Exception is the x E superclass of , L e an v e l 3 instance x E of Level is not 2Ex assignable c epti on to a c clause a t c parameter of type . L e Similarly, v e l 3 x E Level1Exception is also a superclass of Level3Exception , so an instance of Level1Exception is not assignable to a c clause a t c parameter of type . L e The v e l 3 only xE exception type that can be caught by the first c clause a t c h is a . L e The v e l 3 second x E catch clause has a parameter e of type , L e so v e l 2the second xE c clause a t c is able to catch a . L l e 2 The v e Level1Exception is the superclass of . L e An instance of Level is not1Ex assignable c epti v on 2to a c clause a t c l parameter e of type , L e so the second c clause a t c can not v catch 2 a. L e Since lo a Level3Exception ise a subclass i of Lev an vel 2 Exce 1 ptio t n l exception of type Level3Except is assignablei to o na c clause a t c h parameter type . L e All exceptions of type L will e v e l 3 be caught by the first c clause, a t c h so the second c a t c h clause in this program will not have an opportunity to catch a . L e The third c clause a t c has a parameter e of type , Lso the third c clause a t c is able toecatch a L . The exceptions of type L and Level3Exception are assignable to the c clause a t c e parameter of the third catch clause, but the exceptions of those subclass types will be caught by the first two c clauses. a t c h The s statement w i t c h throws a . LThe t block r y e

No.

Remark completes abruptly as control passes to the third c block a t c where d is incremented. The f block i n a is also executed, so f is incremented. The first c block a t c h is able to catch a L or e any subclass of Level3Exception . The second c block a t c h is able to catch a L or e any subclass of Level2Exception . The s statement w i t throws a . L e The t r y 13 e Prints: 0,0,1,0,1 block completes abruptly as control passes to the second c block a t c where c is incremented. The f block i n a is also executed, so f is incremented. g Prints: 1,0,0,0,1 The s statement w i t does not throw an exception; so the s completes w i t c h normally. 14 The subsequent statement increments the variable, a ; and the t block r y completes normally. The f block i n a is also executed, so f is incremented. The try block contains two statements. The first invokes method m1 , and the subsequent statement contains a post increment expression with the variable, a , as the operand. Method m1 throws a WhiteE exception, x c e p n t i so o variable a is 15 d Prints: 0,1,1 not incremented as control passes to the c block a t c h where b is incremented. Although C declares o l o a ColorExceptio in the t clause, h r o w sn a subclass of C is o l ofree to declare only a subclass of ColorExcep in the t clause h r o w sti o n of the overriding method. Compile-time A compile-time error is generated, because the second c clause a t c h attempts 16 f error to catch an exception that is never thrown in the t block. r y At statement h r o w is the first statement in the outer tr block. y At statement h r o w appearing in a try block causes control to pass out of the block. Compile-time 17 f Consequently, statements can not be reached if they appear in the block error after the t statement. h r o The s statement w i t c h that appears after the t statement h r o w is unreachable and results in a compile-time error.

Answer

1) What is an Exception?
An exception is an abnormal condition that arises in a code sequence at run time. In other words, 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 condition that 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 by the 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.

1. Exceptions can be generated by the Java run-time system. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java 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 to the caller of a method.

4) Where does Exception stand in the Java tree 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 that object. 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 wont compile. 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 block in 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 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 exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

throw ThrowableInstance;

ThrowableInstance must be an object of type Throwable or a subclass of Throwable. 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 the types of exceptions that a method might throw.

type method-name(parameter-list) throws exception-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-faqs1.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-faqs1.html on line 195 Warning: main(): Failed opening 'http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html' for inclusion (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 that a 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

ArrayIndexOutOfBoundsException ClassCastException IndexOutOfBoundsException IllegalStateException NullPointerException SecurityException

The types of exceptions that must be included in a methods throws list if that method can generate 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 the divisor 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 the calling 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..." );

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 ) { } } } }

You might also like