07-01 Exceptions and Errors

¡Supera tus tareas y exámenes ahora con Quizwiz!

"Explain the *throw* keyword used in an exception block?"

"*throw* is used to generate an Exception."

"What are the *three blocks* in an *Exception handler*?"

"*try*, *catch* and *finally*."

"What are the three types of exceptions in Java?"

"1. *Checked Exceptions* which are of the sort that an well written program can anticipate and recover from. *FileNotFoundException* for example. 2. *Errors* which are of the sort that are external to the system and are probably unrecoverable. 3. *Unchecked Exceptions (Runtime Exceptions)* which are of the sort that are internal to the system and probably unrecoverable. *ArithmeticException* such as in the case of a divide by zero, *IndexOutOfBoundsException* and *NullPointerException are examples*."

"What are some advantages of exception handling?"

"1. Separates error handling code from regular code. 2. Propagation of errors up the call stack which allows a method's caller to handle it. 3. Grouping and differentiating error types."

"What is an Exception?"

"An Exception is an abnormal condition or an error that arises in a code sequence at run time."

Checked exceptions extend ... and unchecked exceptions extend ... .

*Checked exceptions* extend the java.lang.Exception class. *unchecked exceptions* extend the java.lang.RuntimeException.

What are *errors*?

*Errors are unchecked exceptions* that represent extreme conditions and will *typically cause your application to fail*. Most errors are unrecoverable external errors.

Two things a method must do with a checked exception.

*Handle the exception in a catch{} block* or *throw the exception to the caller method*.

Checked Exceptions List

*IOException* FileNotFoundException ParseException ClassNotFoundException CloneNotSupportedException InstantiationException InterruptedException NoSuchMethodException NoSuchFieldException

*Recognize Common Exceptions*

*Recognize Common Exceptions*

What are *unchecked exceptions*? (*RuntimeExceptions and Errors*) *do not need to be caught*.

*Unchecked exceptions* are the exceptions that are not checked at compile time! The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses, everything else under throwable is checked. - are checked at runtime, not compile time. - unchecked exceptions and errors *do not need to be caught*. - are all subclasses to the RuntimeException class, including RuntimeException itself and all subclasses to the Error class, including Error itself.

*catch*

*catch*

*finally*

*finally*

*try*

*try*

What are *checked exceptions*? *must be caught*

- are checked by the compiler *at compile time*. - *must be caught* by a catch block, or the application will terminate. - are all subclasses to the Exception class; however, *RuntimeException and its subclasses are not part of the Exception class*. - These exceptions maily occur when programming with files and streams.

*Errors*

- represent extreme conditions and will typically cause your application to fail. - unchecked exceptions and errors do not need to be caught.

*COMMON unchecked exceptions include* *RuntimeExceptions*

......*RuntimeExeption*...... *ArithmeticException* *NullPointerException* *IllegalArgumentException* NumberFormatException IllegalThreadStateException *IndexOutOfBondsException* StringIndexOutOfBoundsException ArrayIndexOutOfBoundsException IllegalStateException ClassCastException IllegalMonitorStateException -ArrayStoreException -SecurityException

what are the two issues with this code: void doStuff() { doMoreStuff(); } void doMoreStuff() { throw new IOException(); }

A. the doMoreStuff() method should declare the exception that will be thrown, as follows: void doMoreStuff() throws IOException { ... } B. the doStuff() method should also declare the exception that could be thrown similar to as mentioned above (unless it decides to handle that exception using the try...catch block)

Outline the basic Exception heirarchy, including Errors. .java.lang.Object ..java.lang.Throwable ...java.lang.Error..+..java.lang.Exception ,,,,,,,,,,,,,,,,,,,,,,java.lang.RuntimeException ..............Throwable Error .......................Exception unchecked ... checked..unchecked ......................................Runtime .....................................Exception

An exception is an object of the class java.lang.Throwable. This is the top-level base class. It is a subclass of java.lang.Object. The classes java.lang.Error and java.lang.Exception are subclasses of the class java.lang.Throwable. The class java.lang.RuntimeException is a subclass of the class java.lang.Exception.

ArithmeticException exception * is a runtime exception (unchecked exception)

An exception occurs when you attempt to perform a math operation that yields an exceptional answer. Thrown when division by zero occurs.

InputMismatchException exception

An exception thrown when user input is not as expected.

Name two sublclasses of IndexOutOfBoundsException.

ArrayIndexOutOfBoundsException,StringIndexOutOfBoundsException.

What exception will be thrown with the following code block: String[][] arr = {{"foo", "bar"},null,{"help"}}; System.out.println(arr[2][1]);

ArrayIndexOutOfBoundsException. NullPointerException will not be thrown because the array exsits, the length is 0, so the index is out of bounds.

What is the convention for defining exception classes?

By convention, all exception classes should have a default constructor that doesn't accept any arguments and another constructor that accepts a string argument.

Which are the following valid Java7 exception syntaxes? A. catch (IOException e | SQLException e) B. catch (IOException | FileNotFoundException e) *C. catch (IOException | SQLException e)* D. catch (Exception1 e1 | Exception2 e2) E. catch (IOException | Exception e)

C is correct. B. is wrong because, exception can match only one time. FileNotFound... is a subclass of Both IOException... E is wrong for the same reason. A is wrong because variable e is used multiple times. Same reason for D.

What are the three Exception categories?

Checked exceptions, runtime (or unchecked exceptions), and errors. These three categories share IS-A relationships (inheritance).

*COMMON checked exceptions include*

CloneNotSupportedException, ClassNotFoundException, NoSuchMethodException, IOException, FileNotFoundException, SQLException, InterruptedIOException, and FontFormatException.

*throw*

Exceptions are thrown with the throw keyword.

What is IllegalArgumentException? What class does it extend? Who throws it usually?

Extends RuntimeException when a param passed to a method is not valid. Usually thrown by the application.

What class IndexOutOfBoundsException extend? Who throws it? What are its subclasses?

Extends RuntimeException. Thrown by JVM at runtime. Subclasses: ArrayIndexOOBE and StringIndexOOBE

What is SecurityException? What class does it extend? Who throws it usually?

Extends RuntimeException. Usually thrown by JVM security manager upon security violation. For example, when a java program runs in a sandbox (such as an applet) and it tries to use prohibited APIs such as File I/O, the security manager throws this exception.

What is ClassCastException? What class does it extend? Who throws it usually?

Extends RuntimeException. Usually thrown by JVM when a code attempts to cast an Object of a subclass of which it is not an instance. Example: Object x = new Integer(5); System.out.println((String)x);

What is NullPointerException? What class does it extend? Who throws it usually?

Extends the class RuntimeException. Usually thrown by JVM when an application attempts to use null where an Object is expected. *Example:* String s; System.out.println(s.length()); *Other:* - Calling the instance method of a null object. - Accessing or modifying the field of a null object. - Taking the length of null as if it were an array. - Accessing or modifying the slots of null as if it were an array.

True or False: The catch{} block for a child exception class must FOLLOW that of a parent exception class.

False

True or False: The try{} block can not contain loops or branches.

False

True or False: The finally block can appear before a catch block.

False.

True or False: Trying to call a method recursively without defining an exit condition is not considered an exceptional condition.

False.

True or False; Catch blocks must be followed by one or more finally blocks.

False. A catch block(s) can have zero or one finally block follow them. There can not be more than one finally block.

True of False: A try block must be followed by one or more catch blocks.

False. A try block must have either a catch or a finally block.

Exceptions deklarieren *throws-Klausel*

Java erfordert, dass jede Methode, die eine Exception verursachen kann, diese entweder abfangen oder in der Methodendeklaration den Typ der Exception mit einer *throws-Klausel* angeben muss.

The catch block must be ordered by subtypes first.

NullPointerException * is a runtime exception (unchecked exception)

The class java.lang.NullPointerException extends java.lang.RuntimeException. NullPointerException is thrown by the JVM if you try to access a method or variable of an *uninitialized reference* variable. Thrown when attempting to access an object with a *reference* variable whose *current value is null*. Thrown when you attempt to call null on an operation where an object is required. includes: Calling instance of null object, Accessing or modifying the field of a null object, Taking the length of a null object.

What is ExceptionInInitializerError? What does it extend? Give an example.

Thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable. It extends Error:LinkageError Ex: static int[] x = new int[0]; static { x[0] = 10; }

AssertionError

Thrown when a statement's boolean test returns false.

ExceptionInInitializerError

Thrown when attempting to initialize a static variable or an initialization block.

True or False: The finally block executes regardless of whether the code in the try block throws an exception. A finally block will execute even if a try or catch block defines a return statement.

True.

True or False: Trying to access an array element at a position that is greater than or equal to the array's length is considered an exceptional condition.

True.

*try-catch-finally* Ausnahmebehandler /** *try-Block mit Anweisung, die die Exception auslösen kann* **/ try { //Anweisungen; } /** *Catch ist optional, sofern ein finally-Block folgt** */ /** *Es können mehrere catch-Blöcke hintereinander stehen, um unterschiedliche Exceptions abzufangen** */ /** *Ein Error ist keine Exception und muss separat abgefangen werden** */ /** *catch-Blöcke mit den Fehlerbehandlungsanweisungen (wird nach Typdes Parameters bestimmt!)** */ catch (OutOfMemoryError e) { //Behandlung; e.printStackTrace(); } ....->

catch (RuntimeException e)) { //Behandlung z. B. //IndexOutOfBoundsException, //NullPointerException usw. System.err.println("Offensichtlich ein Programmierfehler!"); throw e; //Leite nach oben weiter } catch (Exception e) { //Fange alle restlichen //Ausnahmefehler ab e.printStackTrace(); } catch (Throwable t) { //Das hier fängt wirklich alles ab t.printStackTrace(); } /** *finally-Block steht immer am Schluss, er wird immer durchlaufen, ist allerdings optional ** */ finally { //Behandlung; //Ob Exception oder nicht, //führe das hier auf jeden Fall //aus. System.out.println("Berechnung beendet oder abgebrochen"); } /** *Nach der Behandlung der Exception wird das Programm fortgesetzt!** */

exception

error that occurs during execution of Java program

ArrayIndexOutOfBoundsException * is a runtime exception (unchecked exception)

extends the class java.lang.IndexOutOfBoundsException, which extends the class java.lang.RuntimeException. In typical programming conditions, the ArrayIndexOutOfBoundsException shouldn't be thrown programmatically. One of the main reasons for the JVM taking the responsibility for throwing this exception itself is that this exception isn't known until runtime and depends on the array or list position that's being accessed by a piece of code. Most often, a variable is used to specify this array or list position, and its value may not be known until runtime. Thrown when a piece of code tries to access an array position out of its bounds, with an invalid index value - an index of an array that does not exist; when an array is accessed either at a position less than 0 (negative index) or at a position greater than (beyond) its length or equal to its length.

IllegalStateException * is a runtime exception (unchecked exception)

java.lang.IllegalStateException extends java.lang.RuntimeException. IllegalStateException may be thrown programmatically. As a programmer, you can throw IllegalStateException to signal to the calling method that the method that's being requested for execution isn't ready to start its execution or is in a state in which it can't execute. For example, you can throw IllegalStateException from your code if an application tries to modify an SMS that has already been sent. Thrown when the state of the environment doesn't match the operation being attempted, e.g., using a Scanner that's been closed.

NoClassDefFoundError * is an Error

java.lang.NoClassDefFoundError extends ava.lang.LinkageError . java.lang.LinkageError extends java.lang.Error. NoClassDefFoundError is thrown by the JVM or a ClassLoader when it is unable to load the definition of a class required to create an object of the class. Don't confuse the exception thrown by Class.forName(), used to load the class, and NoClassDefFoundError thrown by the JVM. Class.forName() throws ClassNotFoundException. ->Thrown when the JVM can't find a class it needs, because of a command-line error, a classpath issue, or a missing .class file.

NumberFormatException * is a runtime exception (unchecked exception)

java.lang.NumberFormatException extends java.lang.IllegalArgumentException. java.lang.IllegalArgumentException extends java.lang.RuntimeException. You can throw NumberFormatException from your own method to indicate that there's an issue with the conversion of a String value to a specified numeric format (decimal, octal, hexadecimal, or binary). Thrown when a method that converts a String to a number receives a String that it cannot convert.

StackOverflowError * is an Error

java.lang.StackOverflowError extends java.lang.VirtualMachineError . Because StackOverflowError extends VirtualMachineError, it should be left to be managed by the JVM. The StackOverflowError error is thrown by the JVM when a Java program calls itself so many times that the memory stack allocated to execute the Java program "overflows." ->Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.)

What are the primary keywords you may see in exception handling statements?

try, catch, throw

"What are the two possible sources of Exceptions?"

"Exceptions can be thrown by the Java run time system or can be generated programmatically by a piece of code."

"You have an Exception handling block that has a try block and a finally block. You call System.exit(0); inside the try block. Will the finally block get called?"

"No. System.exit() does not return. It terminates the JVM."

"What is "Catch or Specify" as it pertains to Exceptions?"

"This means that either an Exception must be caught or the method in which the Exception is generated must specify that it can throw such an Exception. Any subclass of Exception that isn't also a subclass of RuntimeException is subject to "Catch or Specify"."

An abnormal event that occurs during program execution

(Unchecked) Exception

*EXCEPTION HANDLER*

*EXCEPTION HANDLER*

*QUESTIONS*

*QUESTIONS*

Alter the Program Flow

...

Understand the Nature of Exceptions

...

*COMMON unchecked exceptions include* *Errors*

......*Errors*...... AssertionError ExceptionInInitializerError StackOverflowError NoClassDefFoundError

How can you fix the following code to make it compile: import java.io.*; class Great { public void doStuff() throws FileNotFoundException{ } } class Amazing extends Great { public void doStuff() throws IOException, IllegalArgumentException{ } } public class TestClass { public static void main(String[] args) throws IOException{ Great g = new Amazing(); g.doStuff(); } } Select two options: A. Change doStuff in Amazing to throw only IllegalArgumentException. B. Change doStuff in Great to throw only FileNotFoundException as well as IllegalArgumentException. C. Change doStuff in Amazing to throw only IOException. D. Change doStuff in Great to throw only IOException instead of FileNotFoundException.

A and D

What are Checked and Unchecked Exception?

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Checked exceptions must be caught or thrown in the code. Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions do not need to be caught in the code.

Consider the following code... class MyException extends Exception {} public class TestClass{ public void myMethod() throws XXXX{ throw new MyException(); } } What can replace XXXX? Select Three: A. MyException B. Throwable C. No throws clause is necessary D. Exception E. RuntimeException

A, B and D are correct About option C : "No throws clause is necessary": NOT True... It is needed because MyException is a checked exception. Any exception that extends java.lang.Exception but is not a subclass of java.lang.RuntimeException is a checked exception. If the above code threw an unchecked exception (such as a runtime exception), we could get away with not having a "throws" clause in the method declaration.

Given the following code: class Base{ void method1() throws java.io.IOException, NullPointerException{ someMethod("arguments"); // some I/O operations } int someMethod(String str){ if(str == null) throw new NullPointerException(); else return str.length(); } } public class NewBase extends Base{ void method1(){ someMethod("args"); } } select two correct options: A. method1 in class NewBase does not need to specify any exceptions. B. The code will not compile because RuntimeExceptions cannot be given in throws clause. C. method1 in class NewBase must at least give IOException in its throws clause. D. method1 in class NewBase must at least give NullpointerException in its throws clause. E. There is no problem with the code.

A. and E. are correct. Overriding method only needs to specify a subset of the list of exception classes the overridden method can throw. A set of no classes is a valid subset of that list.

what does these commands do? A. java -ea:com.rl.foo.Bar B. java -ea:com.rl.foo... C. java -ea -dsa

A. enables assertion for class Bar B. enables assertion for package foo and all its sub packages C. enable assertions in general but disable assertions for subpackages

A *finally block* is executed when?

Always *after* execution has *left a try block*.

run-time error

An error affecting program execution. Also called an exception.

logic error

An error caused by a statement that is syntactically correct, but produces unexpected or undesired results. Also called a semantic error.

syntax error

An error caused by a statement that violates the rules of Java.

What is the output of this program? * A. - * B. -c * C. -c2 * D. -c22b * F. -2c2b * G. Compilation fails public class Plane { static String s = "-"; public static void main(String[] args) { new Plane().s1(); System.out.println(s); } void s1() { try { s2(); } catch (Exception e) { s += "c"; } } void s2() throws Exception { s3(); s += "2"; s += "2b"; } void s3() throws Exception { throw new Exception(); } }

Answer: B.

What is the result of the code below? A. compilation succeeds B. compilation fails due to error in line B C. compilation fails due to error in line C D. compilation fails due to error in line D E. compilation fails due to error in line E class SubException extends Exception { } class SubSubException extends SubException { } //line A public class CC { void doStuff() throws SubException { } } //line B public class CC2 extends CC { void doStuff() throws SubSubException { } } //line C public class CC3 extends CC { void doStuff() throws Exception { } } //line D public class CC4 extends CC { void doStuff(int x) throws Exception { } } //line E public class CC5 extends CC { void doStuff() { } }

Answer: C The Overridden method CANNOT call a broader exception than the method it is overriding... Line C is using a broader exception than line A Note: lines B, C and E are Overrides line D is Overloaded method, NOT Overridden method

*COMMON (unchecked) errors include*

AssertionError, ExceptionInInitializeError, VirtualMachineError, StackOverflowError, OutOfMemoryError and NoClassDefFoundError.

Avoid catching exceptions ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Avoid catching exceptions you cannot handle. Pretty obvious, but a lot of developers attempt to catch java.lang.Exception or java.lang.Throwable. Since all subclassed exceptions can be caught, the runtime behavior of the application can often be vague when "global" exception classes are caught. After all, one wouldn't want to catch OutOfMemoryError - how should one handle such an exception?

Objects of which of the following classes can be thrown using a throw statement? Select three. A. Event B. Throwable C. Object D. Exception E. RuntimeException

B, D and E are correct.

Bubble the exception if ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Bubble the exception if the method cannot handle it. This is a corollary of the above, but applicable to methods that must catch the exception. If the caught exception cannot be handled correctly by the method, then it is preferable to bubble it.

If the exception hierarchy is A<-B<-C what should be the order of the catch blocks for each exception?

C, B, A. From bottom to top of the hierarchy. If the base exception is listed first, it will cause a compiler error.

Exception that describes a problem that is likely to occur at times.

Checked Exception

Code cannot be placed between the try and catch blocks, try and finally i blocks, or catch and finally blocks—that is, extra code cannot be immediately placed before or after the curly braces that separate the blocks in these statements.

Convert checked exceptions into unchecked ones only when ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Convert checked exceptions into unchecked ones only when required. When wrapping an exception, it is possible to wrap a checked exception and throw an unchecked one. This is useful in certain cases, especially when the intention is to abort the currently executing thread. However, in other scenarios this can cause a bit of pain, for the compiler checks are not performed. Therefore, adapting a checked exception as an unchecked one is not meant to be done blindly.

Which of these assertion syntaxes are valid (choose all that apply)? int x = 5, y = 7; boolean a = true, b = false; A. assert (y > x); B. assert (x > y) : "x = " + x + " y = " + y; C. assert (y == 8) : aReturn(); D. assert(a); E. assert(x); F. assert(x = 1);

E. and F. are wrong.

Consider the following public class TestClass { public static void main(String[] args) { TestClass tc = new TestClass(); tc.myMethod(); } public void myMethod() { yourMethod(); } public void yourMethod() { throw new Exception(); } } What changes can be done to make the above code compile? A. Change declaration of main to : public static void main(String[] args) throws Exception B. Change declaration of myMethod to public void myMethod throws Exception C. Change declaration of yourMethod to public void yourMethod throws Exception D. Change declaration of main and yourMethod to : public static void main(String[] args) throws Exception and public void yourMethod throws Exception E. Change declaration of all the three method to include throws Exception.

E. is the correct answer. java.lang.Exception is a checked Exception. Which means, the method that throws this exception must declare it in the throws clause. Hence, yourMethod must declare throws Exception in its throws clause. Now, since the call to yourMethod in myMethod can also potentially throw an exception, myMethod must also declare it in its throws clause. By the same logic, main method should also declare it in its throws clause. Another alternative is to catch this exception in myMethod: public void myMethod() { try{ yourMethod(); } catch(Exception e){ // since you are catching the exception thrown by yourMethod, there is no need to declare it in the throws clause of myMethod. e.printStackTrace); } }

Either log the exception or bubble it, but don't do both. http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Either log the exception or bubble it, but don't do both. Logging an exception often indicates that the exception stack has been completely unwound, indicating that no further bubbling of the exception has occurred. Hence, it is not recommended to do both at the same time, as it often leads to a frustrating experience in debugging.

#103 True or false? Overloaded methods must not throw new checked exceptions not thrown by the original method.

False. ...

#161 True or false? A method cannot be declared as throwing more than one exception.

False. Any number of exception, separated by commas, can be coded in a throws clause.

#139 True or false? An ArithmeticException is a checked exception.

False. ArithmeticExceptions are considered programmer problems and are NOT checked by compiler. A divide-by-zero error, for example should be checked for your own code. Checked exceptions are also called compile time exception and unchecked exceptions are also called as runtime exceptions.

True or False: Checked exceptions extend Throwable.

False. Checked exceptions extend Exception but are not subclasses of RuntimeException.

True or False: IOException is a runtime exception.

False. IOException extends Exception, it is a checked exception.

True or False. BadStringOperationException is a runtime exception.

False. It directly extends Exception, so it is a checked exception.

True or False. A method must delcare throws on any thrown checked exceptions or their subclasses that are handled.

False. It must decalre throws on the undhandled checked Exceptions or their superclasses.

#140 True or false? if a try-catch construct calls System.exit(), the finally block will execute first.

False. System.exit() means stop the programm now! Even a finally block can't stop that from happening.

#136 True or false? In a try/catch construct, the catch block may be written in any order and the most narrow/specific catch argument is choosen at runtime

False. The catch-blocks must be written in order from most specific to least (e.g. IOException comes above Exception) or the compiler will complain.

#137 True or false? A finally block will only be executed if the exception is no caught.

False. The finally block will ALWAYS run .. unless the try/catch calls System.exit();

True or False: Division by zero will result in a runtime DivisionByZeroException being thrown.

False. There is no DivisionByZeroException. The runtinme exception ArithmeticException is thrown for the divide by zero errors.

# 36 True or false? When you override a method, the overriding method in the subclass must not declare ANY new exceptions not declared by the overriden method.

False. This rule only applies to checked exceptions -- the exceptions which are sublasses of Exception but not subclassens of RuntimeException

Stream type which provides input from a disk file.

FileReader

What happens if a finally block modifies the value returned from a catch block?

If a catch block returns a primitive data type, a finally block can't modify the value being returned by it. If a catch block returns an object, a finally block can modify the value being returned by it.

NOTES: If both catchand finally blocks define returnstatements, the calling method will receive the value from the finallyblock. If a catchblock returns a primitive data type, a finallyblock can't modify the value being returned by it.

If a catchblock returns an object, a finallyblock can modify the value being returned by it. A finallyblock alone wouldn't suffice with a tryblock if code in the try block throws a checked exception. In this case, you need to catch the checked exception or define in the method signature that the exception is thrown, or your code won't compile. The finallyblock can't appear before a catchblock.

What happens if both a catch and a finally block define return statements?

If both catch and finally blocks define return statements, the calling method will receive the value from the finally block.

To handle or throw exceptios?

If the API is developed for our own use, it is better to handle the Exceptions. If your API is used by other applications, it is important that you should pass the information of what went wrong to the calling application. So better declare exception in.

Methods of the Throwable class provide support of gathering information about a thrown exception. The methods getMessage, toString, and printStackTrace are commonly used.

Will this code compile? public void doStuff() { try { // try some risky IO stuff } catch (IOException ex) { // do things throw ex; } }

No, this code won't compile. Eventhough doStuff() method has try catch block to handle exceptions, it is rethrowing the caught exception, and in order to rethrow the exception, you need to declare it in the method signature! So, change the call to: public void doStuff() throws IOException { ... }

Will reassigning a reference variable in a finally clause change the result returned in the try block?

No. The finally block variable works like an instance method parameter in this case.

Will this code compile? try { // do some risky I/O things } catch(IOException e) { //catch the general IO Exceptions e.printStackTrace(); } catch(FileNotFoundException f) { //catch the specific file not found exception f.printStackTrace(); }

No. This code will not compile because specific Exceptions (such as FileNotFoundExceptions) should be caught before the generic exceptions.

Yes or No: Is a program required to catch all exceptions that might happen

No. You can write a program to catch just the exceptions you want.

What are checked vs unchecked Exceptions?

Rule: if e IS-A RuntimeException, or e IS-A Error, then it is unchecked exception; otherwise, it is checked exception. RuntimeExceptions such as NullPointerException are "unchecked" Exceptions, meaning, these Exceptions don't have to be specifically declared or caught or thrown in your code. *Whereas, Exceptions such as IOException or your own custom exceptions need to be declared and caught with proper exception clauses. These are called "checked" exceptions.*

#47 What happens if you divide an integer by a variable with a value of 0; Compiles and runs or Runtime exception or Compiler error

Runtime exception At runtime you will get an ArithmeticalExeption which is no checked for at compile time. Floats and doubles will not thrown an exception if divided by 0! Output: infinity or -infinity

How can runtime exceptions get masked during initialization?

Runtime exceptions arising from any of the following may throw ExceptionInInitializerError: - Execution of an anonymous static block - Initialization of a static variable - Execution of a static method (called from either of the previous two items)

What is IllegalStateException?

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation. Usually thrown by the application.

*throws*

Specifier to be used with a method declared to be terminated when a checked exception occurs within it.

Which of these exceptions are defined by the JRE: StackOverflowError OutOfMemoryError ArrayIndexOutOfBoundError ClassLoadingException CompilationError OutOfStorageError

StackOverflowError and OutOfMemoryError.

StringIndexOutOfBoundsException * is a runtime exception (unchecked exception)

StringIndexOutOfBoundsException extends the class java.lang.IndexOutOfBoundsException, which extends the class java.lang.RuntimeException. Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.

How are error classes defined?

Subclasses of the class java.lang.Error are categorized as errors.

How are checked exceptions classes defined?

Subclasses of the class java.lang.Exception are categorized as checked exceptions *if they are not subclasses of class java.lang.Runtime*.

How are runtime exception classes defined?

Subclasses of the class java.lang.RuntimeException are categorized as runtime exceptions.

checked

The class is a checked exception, which means that it extends java.lang.Exception, but not java.lang.RuntimeException. In other words, it must be declared in the throws clause of any method that may throw it.

unchecked

The class is an unchecked exception, which means it extends java.lang.RuntimeException and therefore does not need to be declared in the throws clause of a method that may throw it.

The common naming convention for catch clause arguments is the representation of a string containing the first letter of each word of the exception being passed.

If a super class method declares a checked throws and a subclass overrides the method with no throws, what does the compiler require regarding try/catch/throws? SuperClass superClass = new SubClass(); superClass.overriddenMethod();

The compiler will assume the method throws the exception.

The finally block is typically used for releasing resources.

The finally block of the try-catch-finally and try-finally statements are always invoked, unless the JVM terminates first.

When an exception is thrown in a try block and there is no matching catch block, this happens.

The method throws the exception to its caller.

The multi-catch feature allows for multiple exception types to be caught in one catch block.

Explain how the inheritance hierarchy of an exception affects how it may be handled when multiple catch blocks exist.

The order in which the catch blocks are placed matters. If the caught exceptions have an inheritance relationship, the base class exceptions can't be caught before the derived class exceptions. An attempt to do this will result in compilation failure.

The throws keyword is used in method definitions of methods that throw an exception.

The try block must contain code that can throw an exception.

The try block must have one catch or finally block.

The try-catch statement is a valid statement that does not include a finally clause.

The try-with-resources statement declares resources that can be automatically closed. The objects must implement AutoCloseable.

The number of finally{} blocks there may be in a try/catch structure.

There must always be one, following the last catch{} block.

Throw exceptions when ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Throw exceptions when the method cannot handle the exception, and more importantly, should be handled by the caller. A good example of this happens to present in the Servlet API - doGet() and doPost() throw ServletException or IOException in certain circumstances where the request could not be read correctly. Neither of these methods are in a position to handle the exception, but the container is (which results in the 50x error page in most cases).

Throw the exception right away. http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Throw the exception right away. This might sound vague, but if an exception scenario is encountered, then it is a good practice to throw an exception indicating the original point of failure, instead of attempting to handle the failure via error codes, until a point deemed suitable for throwing the exception. In other words, attempt to minimize mixing exception handling with error handling.

Both the Error and Exceptions classes are children(subclasses) of this class.

Throwable All exceptions and errors inherit from the Throwable class.

Thrown exceptions move up the call stack until they are caught. If they are not caught and reach the main method, the application will end.

True or False: Trying to execute a method that throws a checked exception without handling the thrown exception causes a compilation error.

True, as long as the throws is not part of the method signature.

True or False: classes that extend Error can be caught and handled.

True, but not recommended because typically these are problems with the JVM the programmer can do nothing to fix.

True of False: FileNotFoundException directly extends IOException.

True, making it also a checked exception.

True or False: An unhandled runtime exception will propagate through the stack and eventual result in an application exit.

True.

# 66 True or false? An exception can be caught by a catch block with an argument type that is superclass of the thrown exception.

True. If there is no catch(ExceptionArgument) wich matches the thrown exception, then an argument which is a superclass of the exception will catch it.

True or False: FileNotFoundException is a checked exception.

True. This exception is thrown if the file that the code is trying to access can't be found.

Use exception class hierarchies for ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Use exception class hierarchies for communicating information about exceptions across various tiers. By implementing a hierarchy, you could generalize the exception handling behavior in the caller. For example, you could use a root exception like DomainException which has several subclasses like InvalidCustomerException, InvalidProductException etc. The caveat here is that your exception hierarchy can explode very quickly if you represent each separate exceptional scenario as a separate exception.

Use subclasses of java.lang.Exception (checked exceptions), when ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Use subclasses of java.lang.Exception (checked exceptions), when you except the caller to handle the exception. This results in the compiler throwing an error message if the caller does not handle the exception. Beware though, this usually results in developers "swallowing" exceptions in code.

Use subclasses of java.lang.RuntimeException (unchecked exceptions) to ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Use subclasses of java.lang.RuntimeException (unchecked exceptions) to signal programming errors. The exception classes that are recommended here include IllegalStateException, IllegalArgumentException, UnsupportedOperationException etc. Again, one must be careful about using exception classes like NullPointerException (almost always a bad practice to throw one).

Wrap exceptions with care. Rethrowing an exception resets the ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

Wrap exceptions with care. Rethrowing an exception resets the exception stack. Unless the original cause has been provided to the new exception object, it is lost forever. In order to preserve the exception stack, one will have to provide the original exception object to the new exception's constructor.

Can exceptions be thrown in catch or finally blocks?

Yes, but if checked exceptions are thrown, then they must be either handled in try-catch or declared with throws in method signature.

Will a finally block execute even if the try or catch block defines a return statement?

Yes.

Can a "RuntimeException" be thrown from any code block without being specified as part of the method's declaration?

Yes. Ex: import java.io.*; class Testyy { public int myMethod1() { // code that throws RuntimeException such as NullPointerException can be added here without any declaration } }

Is the following try syntax right? import java.sql.*; try ( Connection conn = DriverManager.getConnection("host", "db", "pwd"); ) { // do something; }

Yes. This newer try-with-resources syntax is CORRECT even though it does not have a catch or finally block... finally block is implicitly called in this case... It ONLY applies to classes that are "auto closeable" Ex. the following will not work: try (String s = "hi";) { // do something } because String is not auto closeable

You should handle the method as soon as possible, but ... http://stackoverflow.com/questions/3551221/guidelines-on-exception-propagation-in-java

You should handle the method as soon as possible, but it must make sense. If the exception doesn't make sense to be thrown by your method, but you can't handle it, wrap it into another exception and throw this new exception. A bad practice about exception is to catch them all (it's not pokemon, it's java !) so avoid catch(Exception e) or worse catch(Throwable t).

checked exception

an exception that occurs because you have explicitly provided code to terminate the program if a condition is met (use try/catch/finally, or explicit throw new...Exception)

Auslösen von Exceptions in überschriebenen Methoden Will man in einer überschriebenen Methode eine Exception auslösen, so muss diese Exception von der gleichen Klasse oder einer Subklasse der in der Originalmethode angegebenen Exception sein.

class SuperKlasse { public returnTyp MethodenName throws ExceptionXY { ... if (bedingung) { throw new ExceptionXY(); } ... } } class SubKlasse extends SuperKlasse { public returnTyp MethodenName throws ExceptionAB { // Die Angabe von ExceptionAB // in der throws-Klausel // ist nur dann erlaubt, wenn // ExceptionAB Subklasse von // ExceptionXY ... if(bedingung) { throw new ExceptionAB(); } ... } }

OutOfMemoryError * is an Error

is thrown by the JVM when it's unable to create objects on the heap and the garbage collector may not be able to free more memory for the JVM. ->Fatal error that rarely occurs and is beyond your control.

How to enable assertions at runtime using commandline?

java -ea QuickSort.class To disable assertions: java -ea Quicksort.class

The input/output package usually used with Java

java.io

ClassCastException * is a runtime exception (unchecked exception)

java.lang.ClassCastException extends java.lang.RuntimeException. ClassCastException is thrown when an object fails an IS-A test with the class type it is being cast to. *You can use the operator instanceof to verify whether an object can be cast to another class before casting it.* Thrown when attempting to cast a reference variable to a type that fails the IS-A test. Thrown to signal an attempt to cast an object to a class of which it is not an instance.

IllegalArgumentException * is a runtime exception (unchecked exception)

java.lang.IllegalArgumentException extends java.lang.RuntimeException. IllegalArgumentException is thrown to specify that a method has been passed illegal or inappropriate arguments. Even though IllegalArgumentException is a runtime exception, programmers usually use this exception to validate the arguments that are passed to a method, and the exception constructor is passed a descriptive message specifying the exception details. Thrown when a method receives an argument formatted differently than the method expects. Thrown to indicate a method has passed an illegal or inappropriate argument. for example, when using a program that sets radius, this would be thrown if radius is less than 0 since radius can't be negative.

unchecked exception

one that occurs when Java's standard exception-handling methods find an error, which will then terminate the program

Method of an Exception object that prints a list of methods that were called before the exception was thrown.

printStackTrace()

Statement to close a file when the object reader is a FileReader type.

reader.close();

#48 What happens if you put this expression in your code: int x = 0; int y = 4 % x; compiler error or runtime exception or compiles and run

runtimes exception. The modulo operator (%) is performing a divide, so you get a divide-by-zero ArithmeticException at runtime. Even using a literal 0 ( int y = 4 % 0;) instead of a variable would not cause a compiler error.

IndexOutOfBoundsException * is a runtime exception (unchecked exception)

that's thrown when a piece of code tries to access a list position that's out of its bounds—when the position is either less than 0 or greater than or equal to the list's size. What is thrownd during execution if a negative value is ued for an array index. Same as ArrayIndexOutOfBounds, however is used on lists


Conjuntos de estudio relacionados

W02 Connect Learn Smart: The Market System (Extra Credit)

View Set

AWS Certified Cloud Practitioner - Course Questions

View Set

Environmental Science Chapter 15

View Set

L11 Compression, System Backup, and Software Installation

View Set