Exception Handling

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

String string = "animals"; System.out.println(string.indexOf("al", 5)); What gets printed? why?

-1, this lets you know that it couldn't find this value in the search.

Why doesn't float literals divided by zero throw an exception?

0.0 is a double literal and this is not considered as absolute zero! No exception because it is considered that the double variable large enough to hold the values representing near infinity!

String string = "animals"; System.out.println(string.indexOf('a', 4)); What gets printed?

4

How does a programmer know to put a method inside a try block? When should you put something in a try block?

A programmer will know to put something in a try block if it is a checked exception which forces the user to either throws the exception or handle it within the method. Now, a programmer will not know to put an uchecked exception in a try catch because the compiler doesn't force you. So how do you handle something you can't see? You either look at the api documentation or you dont handle it. During testing the bug will come up and you can handle it then. You have to put a checked exception in a try block. You should put unchecked exceptions in a try block if you know they could occur. (Such as you getting user input, not knowing what the user could input)

What does the throw keyword do?

A throw statement abruptly terminates the execution of the current method, and returns control right back to the caller, forcing them to deal with the error, or rethrow the exception up the chain.

Define an exception.

An exception is really just an object that represents an error or condition that prevents the program from executing normally.

How can the throw statement be analogous to a method call?

Because in a way it calls a catch block

Why would a lazy programmer want to throw an unchecked exception instead of checked exception.

Because they don't have to handle the unchecked exception.

How is IllegalArgumentException and NumberFormatException thrown by the programmer?

Because whoever wrote that method, such as Integer.parseInt(), made sure that if you put letters or invalid characters that their method would throw a number format exception. Exceptions thrown by the JVM are not thrown in the method but by the jvm itself when it sees it.

If the exception class belongs to the class Throwable, why not use throwable to catch all mistakes including the errors subclass?

Because you shouldn't try to handle errors. There is no way to recover for them. Example: your disc drive disappears. You as a programmer cannot handle that!

Why don't unchecked exceptions need to be caught?

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

What is a checked exception?

Simple: An exception that occurs at the compile time. More Detail: A checked exception is a type of exception that must be either caught or declared in the method in which it is thrown. For example, the java.io.IOException is a checked exception. In the Java class hierarchy, an exception is a checked exception if it inherits from java.lang.Throwable, but not from java.lang.RuntimeException or java.lang.Error. All the application or business logic exceptions should be checked exceptions.

What is the one thing that can stop a finally block from being executed?

System.exit(0);

What are the three ways to print an exception?

System.out.println(ex); //1 //prints exception type with message System.out.println(ex.getMessage()); //2 //Prints just the message that was put in the parameters of the exception thrown. ex.printStackTrace(); //3' //shows where the exception occurred in each method that it passed through

What is the result of this code: 26: try { 27: throw new RuntimeException(); 28: } catch (RuntimeException e) { 29: throw new RuntimeException(); 30: } finally { 31: throw new Exception(); 32: }

The exception in line 29 will be forgotten and only line 31 will be printed.

If an exception is not caught and it also has a finally clause with the rest of the program afterwards, what happens?

The finally always gets executed regardless if anything is caught or uncaught(code in try statement worked fine or catch statements did not match exception). In this scenario the exception was uncaught due to not finding a matching catch statement which will result in an exception being printed with its stackTrace. This means the rest of the program will not even be executed. To clarify, right after the finally clause the program is terminated due to an exception that was not handled.

Why do you need a try block if the throw keyword calls the catch block?

Think about it. What would happen if you got rid of the try block and just had catch. There will be no way to handle the method because how does java know you are trying to handle this method. It cannot be put in the catch block either because the catch block is what happens if you do catch an exception!

ExceptionInInitializerError

Thrown by JVM when attempting to initialize a static variable or an initialization block. Example: static { int[] countsOfMoose = new int[3]; int num = countsOfMoose[-1]; } B/c this cant be initialized & it belongs to the class (static), java cannot continue. This is why this an error.

Define NoClassDefFoundError

Thrown by the JVM when a class that the code uses is available at compile time but not runtime

Define StackOverflowError

Thrown by the JVM when a method calls itself too many times (this is called infinite recursion because the method typically calls itself without end) When Java calls methods, it puts parameters and local variables on the stack. After doing this a very large number of times, the stack runs out of room and overfl ows. This is called a StackOverflowError. Most of the time, this error occurs when a method calls itself. public static void doNotCodeThis(int num) { doNotCodeThis(1); }

Define ClassCastException

Thrown by the JVM when an attempt is made to cast an exception to a subclass of which it is not an instance

Define ArithmeticException

Thrown by the JVM when code attempts to divide by zero Even a zero divided by zero!

Define ArrayIndexOutOfBoundsException

Thrown by the JVM when code uses an illegal index to access an array

Define NullPointerException

Thrown by the JVM when there is a null reference where an object is required

Define IllegalArgumentException

Thrown by the programmer to indicate that a method has been passed an illegal or inappropriate argument public static void setNumberEggs(int numberEggs) { if (numberEggs < 0) throw new IllegalArgumentException( "# eggs must not be negative"); this.numberEggs = numberEggs; } The program throws an exception when it's not happy with the parameter values. The output looks like this: Exception in thread "main" java.lang.IllegalArgumentException: # eggs must not be negative

Define NumberFormatException

Thrown by the programmer when an attempt is made to convert a string to a numeric type but the string doesn't have an appropriate format Example: Integer.parseInt("abc"); You needed to pass a string that was numbers. Not letters.

Define FileNotFoundException

Thrown programmatically when code tries to reference a file that does not exist Thrown by the programmer

Define IOException

Thrown programmatically when there's a problem reading or writing a file Thrown by the programmer

Try, catch and finally must always be in this order in your code. True or false

True

a caller in a try block can never have a checked exception in its catch's parameters if the caller in the try block doesn't throws the checked exception. True or false?

True

Difference bewtween checked and unchecked exceptions?

Unchecked exceptions are the same as runtime exceptions. They do not cause any compile time error. Java does not force you to handle these exceptions. Why? Because almost every method could have runtime exceptions and it would make code look poopy. Checked exceptions must be handled, java forces you. They will have a comple time error. the biggest difference between checked and unchecked exceptions is that checked exceptions are forced by compiler and used to indicate exceptional conditions that are out of the control of the program (for example, I/O errors), while unchecked exceptions are occurred during runtime and used to indicate programming errors (for example, a null pointer).

If a try statement has multiple catch blocks, at most one catch block can run. Java looks for an exception that can be caught by each catch block in the order they appear, and the first match is run. What if a try statement has multiple exceptions?

Whatever exception appears first is what will go to the catch blocks to try and find that one match.

Explain rules regarding subclasses & exception declarations

When a method overrides a method in a superclass or interface, it is not allowed to add checked exceptions. It is allowed to declare fewer exceptions or declare a subclass of a declared exception. Unchecked exceptions can be added to any overrided method with no problem.

When do you need to handle unchecked exceptions/ runtime exceptions? Do you need to handle unchecked exceptions/ runtime exceptions?

When you know something may cause a runtime error such as getting input from a user who could enter an invalid response. Most of the time you don't need to handle these exceptions because most if these exceptions ever do occur, it is the programmers fault. For example: if you write code that divides 10 by 0, you will have a runtime exception. But as a programmer you should know that. But if a user is giving you numbers to put, then you can handle the scenario where they input 0 has the divisor!

Can you handle java.lang.errors?

Yes but it is not a good idea

Can you throws errors?

Yes but not advised!

Are errors exceptions? If they are, what kind are they?

Yes, Unchecked

When should checked exception be used and when should unchecked exceptions be used?

Checked Exceptions should be used for predictable, but unpreventable errors that are reasonable to recover from. Unchecked Exceptions should be used for everything else. Predictable but unpreventable: The caller did everything within their power to validate the input parameters, but some condition outside their control has caused the operation to fail. For example, you try reading a file but someone deletes it between the time you check if it exists and the time the read operation begins. By declaring a checked exception, you are telling the caller to anticipate this failure. Reasonable to recover from: There is no point telling callers to anticipate exceptions that they cannot recover from. If a user attempts to read from an non-existing file, the caller can prompt them for a new filename. On the other hand, if the method fails due to a programming bug (invalid method arguments or buggy method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.

What are errors in java?

Errors extend the error class from the throwable hierarchy. You should not try to handle errors. It usually means something horribly went wrong!

What kind of error are Exceptions?

Exceptions are runtime errors.

True or false, if finally and catch both throw exceptions, the exception thrown will be the one in the catch block since it comes first.

False. Finally is always executed after the try catch blocks and it has the final say. Java will forget about the exception in the catch block.

How does throw interrupt the normal flow of execution?

If the throw keyword is called, the exception automatically gets thrown to the caller inside the try block. After the exception is handled, the program continues right after the catch block. Notice how we never went back to finish the rest of the method that threw the exception. This is how the normal flow is interrupted. The method never fully carries out its intended purpose if something is thrown.

When is arithmeticException thrown by double?

If you do 0.0/0.0 which is undefined.

What does it mean to "throw an exception"?

It simply means you are passing the exception from one place to another.

An element is not found when searching a list. Is it a good idea to use an exception for this?

No b/c this usually returns -1 or null. Keep in mind this is not asking about an ArrayIndexOutOfBoundsException

If you throw a checked exception, does it have to contain the keyword throw in the method definition? Why or why not?

No because maybe in future code you will implement a throw keyword. The compiler realizes this and makes the programmer deal with it themselves.

Can you have two catch blocks with the same exception? Can you have a catch (subclass exception) below a super class(superclass exception)?

No there will be a compile error because one of them becomes unreachable. No, because the superclass will always catch the exception that the subclass will catch making the subclass catch block unreachable causing a compile error.

If a method has throw new exception in its definition, does the caller have to be in a try block?

No. If the exception is a runtime/unchecked exception then no. If it is a checked exception then the caller can just put throws in its own methods signature. If they don't, then they have to put in a try catch statement.

Do errors from the throwable hierarchy have to be handled if they are thrown?

Nope. Do not try to handle errors! But you can if you want. Good Luck!

Which syntax is correct: //1 catch(Exception e){ throw e; } or //2 catch(Exception e){ throw new exception e(); } or //3 catch(Exception e){ throw new ArithmeticException(); }

Option 1 and 3 are correct.

Why don't you have to handle a method that contains throw new RuntimeError() in its definition ?

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can). This is why the throws keyword isnt needed for unchecked exceptions but you can always put it for good practice.

When a method throws a checked exception, what two options are available to you concerning handling exceptions? Give an imaginary situation to go along with it.

You can either deal with the exception within the method(try, catch statement), or you can make it the calling codes problem(throw it). As an example, think of Java as a child who visits the zoo. The happy path is when nothing goes wrong. The child continues to look at the animals until the program nicely ends. Nothing went wrong and there were no exceptions to deal with. This child's younger sister doesn't experience the happy path. In all the excitement she trips and falls. Luckily, it isn't a bad fall. The little girl gets up and proceeds to look at more animals. She has handled the issue all by herself. Unfortunately, she falls again later in the day and starts crying. This time, she has declared she needs help by crying. The story ends well. Her daddy rubs her knee and gives her a hug. Then they go back to seeing more animals and enjoy the rest of the day. These are the two approaches Java uses when dealing with exceptions. A method can handle the exception case itself or make it the caller's responsibility. You saw both in the trip to the zoo.

What's the output of the following: 30: public String exceptions() { 31: String result = ""; 32: String v = null; 33: try { 34: try { 35: result += "before"; 36: v.length(); 37: result += "after"; 38: } catch (NullPointerException e) { 39: result += "catch"; 40: throw new RuntimeException(); 41: } finally { 42: result += "finally"; 43: throw new Exception(); 44: } 45: } catch (Exception e) { 46: result += "done"; 47: } 48: return result; 49: }

before catch finally done

True or false: Just like a for-loop a try statement doesn't have to have curly braces?

false! Try statements must have curly blocks.

Name the common 13 String methods.

length() charAt() indexOf() substring() toLowerCase() toUpperCase() equals() equalsIgnoreCase() startsWith() endsWith()

How is try catch and throw usually used?

throw is used in the method definition. throw, passes the exception to the caller. Wherever that method was called, is the caller. Now, the caller should be in a try block. The try block contains the code that executes "normally" if an exception isn't thrown. If an exception was thrown then the catch block will catch it and take care of it.


Ensembles d'études connexes

Med success genitourinary comprehensive exam

View Set

OWare- Essentials Of Communication 2. Language Characteristics

View Set

Community Ambulance Cancel Codes (800 codes)

View Set

Lecture Chapter 13 Brain and Spinal Cord

View Set

Fundamentals: Chapter 15: Critical Thinking in Nursing Practice

View Set

CH13: Altered Hormonal and Metabolic Regulation

View Set

ACC 3120 study cards WITHOUT calculated problem

View Set

California Legal Aspects of Real Estate Chapter 14

View Set

Social. Studies: Western Europe Lesson 1. Physical Geography of Western Europe.

View Set