Quiz 8: BufferedReader, Exceptions, Concurrency (3 days worth)

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

Multithreading

Allows different parts of a single program to run concurrently.

Some common exceptinos

ArrayIndexOutOfBoundsException FileNotFoundException NullPointerException FileIOException

What do you have to do for code that can throw checked exceptions?

Catch with a try/catch statement -- OR -- List the exception in the throws clause of any method that may throw or propagate it Otherwise, will not compile.

If you have no handler for input/output, what happens?

Compiler error? Has to do with exception hierarchy...an CHECKED exception

start() method

Creates a new thread You have to call t.run() and t.start() for the thread to get going .

Exception Handling

Ex. tried to open a file but no such file exists. We want to build this into our program. Then, we can note problem and continue or terminate gracefully. Allows for grouping of types of exceptions.

If there is no handler for an arithmetic exception, will compiler complain?

It will compile! But this is still a problem. Has to do with exception hierarchy...an UNCHECKED exception

Where can you find a list of exceptions to include?

Java API. Each method has what the method "Throws:"

Exception Hierarchy (tree)

Object -- > Throwable -- > Error -- >, or Exception --> ... Runtime Exception is an Exception .. goes on in a tree

Call Stack

A place in memory that stores information about methods that are running/executing Contains "stack frames" Can "push" and "pop" stack frames

ExceptionScope - how would you change it so that the exception is caught in main?

Add a try-catch block to main. Is this bad practice?

ExceptionScope - how would you change it so that the exception is caught on level 3?

Add a try-catch block to the body of the method. Then, the exception will be caught immediately after it occurs.

Checked Exceptions

Should be anticipated by programmer Ex. unable to open a file Must deal w/ these exceptions in the program, and think about how to handle this exception situation. This is enforced by the compiler. "Errors that you can recover from"

Order of Exceptions

Start from specific to most generic exception. The order of the catch blocks matter! Good practice to include a finally catch (Exception e), which is the parent class to all exceptions. But if you do it in the wrong order, the parent will catch everything and we will never get any granularity from our various exception blocks.

Exception propagation goes through the Call Stack:

Suppose main: is where a method is called. Suppose an exception happens at some level of the call stack. if the method has an exception handler, it will handle the exception. If not, then it will pass through the call stack until it reaches the topmost method with an exception handler. The main shouldn't have an exception handler because it is at the top of the call stack.

How exceptions propagate

The call stack searches for a method that can hanlde the exception. Then, it goes through the call stack in reverse order

What will happen if an exception is ignored?

The program terminates and prints stack trace This indicates the line and method call trail Should not be in the final version of your program

ExceptionScope class + Propagation class .. demos the way that exceptions propagate through levels. // Level 3 method has an exception, passes it to Level 2 method, and Level 1 method is the one to actually catch it.

public class ExceptionScope { public void level1() { try { level2(); } catch (ArithmeticException problem) { print stuff... } } public void level2() { level3(); } public void level3() { int num =10; denom = 0; int result = num/denom; } } // Main calls level1 method: public class Propagation { static public void main (String[] args) { ExceptionScope demo = new ExceptionScope(); demo.level1(); } }

Examples of Custom Exceptions: Alien modified class that throws InvalidAlienGreetingException

public class InvalidAlienGreetingException extends Exception { public InvalidAlienGreetingException() { // Constructor; print ("Exception...Invalid greeting"); } @Override public STring getMessage() { return "Can't do htat."); } } ******************* public class SpaceCreatures { main { try { Alien a1 = new Alien("SLKD", "SDF"); a1. speak(); Alien a2 = new Alien("sldk", "df"); a2. speak(); Alien a3 = new Alien("dk", "d"); a3. speak(); } catch (InvalidAlienGreetingExceptoin e) { print e; }}

ArithmeticExceptionDemo.java // Demo of a try statement

public static void main(String[] args) [ int a = 5; int b = 0; try { int c = a / b; print c; } catch (ArithmeticException e) { print "Can't divide by 0 you dummy!"; } }

flush() method

handles buffering I think it closes everything within the try-with-resources block?

"Swallowing the exception"

if the catch block contains no statements: try { // FileNotFoundException occurs } catch (FileNotFoundException e) { } // twas empty!! D:

- What if you want to print Done when you are truly done?

- t1.join(); - t2.join();

PrintTask.java

-- Creates two Thread objects, t1 and t2. Then, the threads are starte din the main() and hte .start() methods are called on both of them. - If you run it repeatedly, there is random ordering of each thread - Depending on the runtime, you can also get t1, t2, and main running concurrently...001122Done, or 010122Done, or 00Done1212 - but within each thread, each sequence is fixed so you won't get 02211...

throws keyword example. I still dont get where the exception has been handled?

// THen in main! Handles it:? psv MAIN() { try { readSingleLine(); } catch (IOException e) { print e.getMesage(); } }

What will happen if exception of type 2 occurs in statement 1? try { statement1; statement2; } catch (ExceptionType1 e) { // statements executed when exception is thrown } finally { statement3; } statement4;

????????

What will happen if exception of type 2 occurs in statement 1? try { statement1; statement2; } catch (ExceptionType1 e) { // statements executed when exception is thrown } finally { statement3; }

??????????

throws keyword

A keyword that can be included in the definition of a method. Tells Java that this code can throw a certain type of exception. The, one of the methods in the body of the method will handle it.

call stack trace

A message that is printed if an exception is ignored / program is terminated. This indicates the line on which the exception occurred and shows the method "call trail"

Reading from the file with Buffered Reader: 1. Create a new FileInputSTream fs 2. Create a new BufferedREader and InputStreamReader that takes the fs 3. Read with a while loop 4. Handle exceptions

FileInputStream fs = new FileInputStream(filename, "UTF-8"); BufferedReader r = new BufferedReader (new InputStreamReader(fs); String line; while ((line == reader.readLine()) != null) { print line; // Does not yet handle exceptions!

Unchecked Exceptions

Fundamental problems in your logic Under RunTimeException and Error class. Cases where it is better to fix the bug directly. Ex. NullPointer exception. You have something off. Ignoring that would be bad...you'd be "swallowing" it and not letting it be accessed by a higher level.

Exception propagation

If it is not appropriate to handle an exception where is has occurred, then it can be handled at a higher level. The exception will propagate through the method calling hierarchy. Until they are caught and handled or until they reach the level of the main method.

File Input STream / InputStreamReader / FileReader

Reads raw bytes Reads character by character

What happens after an exception is thrown?

They must be caught or handled by another piece of code 3 ways: - Ignore it - Handle it where it occurs - Handle it at another place in the program

Why is try-with-resources useful?

This lets the program close your resources for you. If multiple Resources are inside parentheses,

Custom Exceptions

Throw a custom exception when something goes wrong. See InsufficientFundsException, BankAccount 1. WRite a class InsufficientFundsException that extends class Exception. 2. In class BankAccount, define the method withdraw and you can include the throws keyword: public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(amount, "Messgae..."); this.balance -= amount; }}

All Error and Exception classes are descendants of the___________- class.

Throwable

Example of a call stack involving two methods: main() calls the method square(5) // At each time point, the call stack goes in forward, then reverse order.

Time 0: Empty Stack Time 1: push main(). Main is in the stack. Time2: push: square(5). Main is still in the stack, and now square is on top of it. Time 3: Pop: square(5) when it returns a value. Method exits. Now, only main() is on the call stack. Time 4: Pop: main() returns a value. Method exits. Call stack is empty gain. *** SEE THIS SLIDE VERY IMPORTNAT*

try-with-resources statement

a Try statement that declares one or more Resources This ensures that each resource is closed at the end of the statement.

stack frames

stores return address, local variables, and parameters. When a method is called, the stack frame is pushed onto the call stack.

Why use try with resources?

aka creating new File inside the parentheses of new PrintWriter, for example. Allows us to automatically close. using .flush method on the outer thing will close everything inside, too.

exception object

an event created by the Java Virtual Machine, when something happens in the program that disrupts the flow Creates an exception object, which we can call "e" or something. Method hands it off to the runtime system.

Resource

an object that must be closed after the program is finished using it. Examples: - File - BufferedReader

Wrapping an exception

catch (NoSuchMethodException e) { throw new MyServiceException("Couldn't process request", e); }

throw keyword......not to be confused with throws keyword! How would you throw an exception using the throws keyword?

ex. public int remove(Node prevNode) { if (prevNode == null) { throw new ILlegalException ("Previous node is null."); ... }

Buffered Reader

faster than Scanner More efficient b/c of buffering Can read a line at a time instead of characters

try / catch / finally block

like our familiar try-catch block, but the finally statement will execute whether things went normally or not. Example - closing your BufferedReader should be in a finally block (unless you are using a try-with-resources ) Finally clause is of course, optional. But if included, it will be executed after the statements in the try block.

"dereferenced"

means no one is pointing at the vairable

FileIOExTryWithResources (exceptions exampe 2) // Reads lines from input file & writes them to the output file // Demonstrates writer.println(line) method; and writer.flush(); // No need to close FileReader, BufferedReader, or PrintWriter because we used try with resources & they will be closed automatically.

public static void readAndPrint(String input, String output) { try (FileReader f = new FileReader(input); PrintWRiter writer = new PrintWriter(new FileWRiter(output))) { BufferedReader br = new BufferedReader(f); STring line; while ((line = br.readLine()) != null) { print line; writer.println(line); } } writer.flush(); catch (IO exception e) { print "Exception" + e; then in main: readAndPrint("myFile.txt", "out.txt");

FileIO example.java (Under Exceptions) // Demonstrates using BufferedReader to read from the file, and PrintWriter to print to a file. // Reads lines from input file and saves to an output file // Demos .flush() method // Exceptions too // No need to close FileReader, BufferedReader, or PrintWriter because we used try with resources & they will be closed automatically.

public static void readAndPrint(String input, String output) { try (FileReader f = new FileReader(input); PrintWriter writer = new PrintWriter(new FileWriter(output))) { BufferedReader br = new BufferedReader(f); String line; while ((line = br.readLine()) != null) { print "Line "+ line; writer.println(line); } writer.flush();

FileIO example.java (Under Exceptions) // Demonstrates using BufferedReader to read from the file, and PrintWRiter to print to a file. // Reads lines from input file and prints * Demos finally block!

public static void readFromFile(String input) { Buffered Reader br = null; try { FileReader f = newFileReader(input); br = new BufferedReader(f); String line; while ((line = br.readLine()) != null) { print line; } } catch (IO Exception e) { print e.getMessage()) } finally { try { br.close(); } catch (IO exception e) { print "Exception"'; } }

FileIOExTryWithResources (exceptions example 1) // Reads lines from input file & prints // Demos BufferedReader to read from file, and PrintWriter to print to a file

public static void readFromFile(String input) { // Using try with resources: try (FileReader f = new FileReader(input)) { BufferedReader br = Files.newBufferedReader(Paths.get(input), Charset.forName("UTF-8")); String line; while ((line = br.readLine()) != null) { print line; } } catch (IO exception e) { print e.getMessage(); } }

throws keyword example

public void readSingleLine() throws IOException { FileReader f = new FileReader("file.txt"); BufferedReader br = new BufferedReader(f); String line = br.readLine(); print line; br.close(); }

What is buffering?

reading the hard drive in such a way that they can access a line at a time! Faster

For a try-catch-finally block, if there are no exceptions, what happens?

skips catch block. Always goes to finally block.

exception object e contains

the state of the program when the error occurred Where it occurred on the calstack

imlements Runnable

this interface contains the run() method.

BufferedReader try-with-resources example

try (BufferedReader reader = Files.newBufferedReader(path,Charset.forName("UTF-8"))) { STring line = null; while ((line = reader.readLine()) != null) { print line; } } catch (IO Exception e) { print e; }

Catching multiple exceptions in one catch block

try { ... } catch (PrintException | IOException e) { print e.getMessage(); }

When a method returns, what happens?

we "pop" the stack frame. Then, control goes to the method that called it.

run() method

where a Java program begins. Used in multithreading.


Conjuntos de estudio relacionados

Wellness Chap. 2 Behavior Change

View Set

CH. 4 The Market Forces of Supply and Demand

View Set

Capsim Exam Study Guide--Business Policy (Williamson)

View Set