exceptions an exception is an object that describes an unusual or erroneous situation exceptions are...

39
Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program

Post on 21-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Exceptions

An exception is an object that describes an unusual or erroneous situationExceptions are thrown by a program, and may be caught and handled by another part of the program

Page 2: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Exception HierarchyErrors:

Errors are caused by bugs in the Java VM, or by the program running out of memory or other resources.

Errors are usually not handled by programs.

Exceptions: Exceptions can be caused by bugs in the program or

improper data supplied to the program Exceptions should be handled, or caught An exception is either checked or unchecked Checked exceptions must be caught or declared as thrown. You are not required to handle unchecked exceptions.

Page 3: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Exception Handling

Try-catch block and finally block

try {   // code may cause/throw exceptions } catch (Exception1 e1) {   // handle Exception1 } catch (Exception2 e2) {   // handle Exception2 } finally {   // optional   // code always executed whether an exception // is thrown or not }

Page 4: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Define Your Own Exception

public class MyException extends Exception {   public MyException(String msg) {     super(msg);   } }

Page 5: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Throw Statement and Throws Clause

public class MyClass {   public void aMethod(int i, int j)     throws MyException {     // ...     throw new MyException(reason);     // ...   } }

Page 6: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

I/O Streams

A stream is a sequence of bytes.In a program, we read information from an input stream and write information to an output streamAn I/O stream is either a character stream, which deals with

text data byte stream, which deal with binary

data

Page 7: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Two Types of I/O

Stream-based I/O supports reading or writing data sequentially. A stream may be opened for either reading or writing,

but not both.

Random access I/O supports reading and writing data at any position of a file.

A random access file may be opened for both reading and writing.

Page 8: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Standard I/O Streams

There are three standard I/O streams:standard input – System.instandard output – System.outstandard error – System.err

Page 9: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Some classes used for I/O

FileInputStream Reads bytes from a file

Reader Abstract class for reading character streams

InputStreamReader

Reads bytes & translates into characters

BufferedReader Read character-input and builds lines or arrays

StreamTokenizer Parse strings into tokens

OutputStream Abstract class to outputting bytes

FileOutputStream Write data to a file

Writer Write character streams

Page 10: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Common Text Input Combinations

Read character at a time from a text file

FileInputStream(fileName)InputStreamReader

Read one line at a time from a text file

FileInputStream (fileName)InputStreamReaderBufferedReader

Read one word at a time from a text file

FileInputStream (fileName)InputStreamReaderBufferedReaderStreamTokenizer

Read Keyboard input InputStreamReader(System.in)BufferedReader

Read int, double, etc. from a non-text file

FileInputStream(fileName)DataInputStream

Page 11: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

I/O Program Examples

ReadCharacters.javaReadLines.javaReadWords.java

Page 12: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Reading/Writing Text Files

The reader and writer classes can handle text I/O. Handle conversion between Unicode and native character encodingMay throw IOExceptionBufferedReader in    = new BufferedReader(        new FileReader("foo.in")); PrintWriter out    = new PrintWriter(        new BufferedWriter(          new FileWriter("foo.out")));

Page 13: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: InventoryItem.java

import java.text.DecimalFormat;public class InventoryItem { private String name; private int units; private float price; private DecimalFormat fmt; public InventoryItem(String itemName, int numUnits, float cost) { name = itemName; units = numUnits; price = cost; fmt = new DecimalFormat ("0.##"); } public String toString() { return name + ":\t" + units + " at " + price + " = " + fmt.format ((units * price)); }}

Page 14: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: Inventory.javaimport java.util.StringTokenizer;import java.io.*;public class Inventory { public static void main (String[] args) { final int MAX = 100; InventoryItem[] items = new InventoryItem[MAX]; StringTokenizer tokenizer; String line, name, file="inventory.dat"; int units, count = 0; float price; try { FileReader fr = new FileReader (file); BufferedReader inFile = new BufferedReader(fr); line = inFile.readLine();

Page 15: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: Inventory.javawhile (line != null) { tokenizer = new StringTokenizer (line); name = tokenizer.nextToken(); try { units = Integer.parseInt(tokenizer.nextToken()); price = Float.parseFloat(tokenizer.nextToken()); items[count++] = new InventoryItem(name, units, price); } catch (NumberFormatException exception) { System.out.println("Error in input. Line ignored:"); System.out.println(line); } line = inFile.readLine();}inFile.close();

Page 16: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: Inventory.java for (int scan = 0; scan < count; scan++) System.out.println(items[scan]); } catch (FileNotFoundException exception) { System.out.println("The file " + file + " was not found."); } catch (IOException exception) { System.out.println(exception); } }}

Page 17: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: Inventory

Input Output

Widget 14 3.35Spoke 132 0.32Wrap 58 1.92Thing 28 4.17Brace 25 1.75Clip 409 0.12Cog 142 2.08

Widget: 14 at 3.35 = 46.9Spoke: 132 at 0.32 = 42.24Wrap: 58 at 1.92 = 111.36Thing: 28 at 4.17 = 116.76Brace: 25 at 1.75 = 43.75Clip: 409 at 0.12 = 49.08Cog: 142 at 2.08 = 295.36

Page 18: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: TestData.javafinal int MAX = 10;int value;String file = "test.dat";FileWriter fw = new FileWriter(file);BufferedWriter bw = new BufferedWriter(fw);PrintWriter outFile = new PrintWriter(bw);for (int line=1; line <= MAX; line++) { for (int num=1; num <= MAX; num++) { value = (int) (Math.random() * 100); outFile.print(value + " "); } outFile.println();}outFile.close();

Page 19: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: TestData Output12 92 80 25 40 10 25 82 89 17 20 12 34 69 27 4 43 50 39 64 43 4 13 83 68 63 12 50 36 20 32 41 35 20 7 50 89 67 68 49 90 25 54 59 30 88 61 92 28 1 45 57 50 6 95 90 66 17 6 27 0 86 19 70 75 21 98 30 80 19 54 93 54 31 43 54 74 35 10 92 47 12 79 2 82 33 22 81 44 26 95 90 77 76 63 16 12 30 89 60

Page 20: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

JDBC

Java Database ConnectivitySteps:1. Load a JDBC driver2. Establish a connection with a data

base3. Send queries and update statements4. Process the results

Page 21: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Setting up an Access Database Driver for Windows

Open the “ODBC Data Sources (32 bit)” folderStart|Settings|Control Panel|ODBC Data Sources (32 bit)

Select the System DSN tab (top of the dialog box)Click on the Add… button (at the right) Select Microsoft Access Driver(*.mdb) from the list boxClick “Finish”A dialog box with the title ODBC Microsoft Access Setup will appear,

Type a description in the Description Text field (optional) In the Database section,

click on the Select button, find and select your saved version of the access.mdb database, Click OK

Click OK in the ODBC Microsoft Access Setup DialogThe System DSN section of the initial ODBC Data Source Administrator dialog should now have the new mdb database name in the list of system data sources.

Page 22: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

The UserPass Table

username password

Bill Gates blue

Scott McNealy lavender

Steve Jobs aqua

Page 23: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: BuildUserDB_Access.javaimport java.sql.*;import java.io.*;import java.util.*;public class BuildUserDB_Access { public static final String database = "Access 2000"; public static final String jdbcDriver = "sun.jdbc.odbc.JdbcOdbcDriver"; public static final String dataSource = "jdbc:odbc:";

public static void main(String args[]) { String dbName = "Users"; String tableName = "UserPass"; Connection conn = null; Statement stmt = null;

Page 24: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: BuildUserDB_Access.javatry { Class.forName(jdbcDriver);} catch(ClassNotFoundException e) { System.exit(1);}try { String url = dataSource + dbName; conn = DriverManager.getConnection(url); stmt = conn.createStatement();} catch (SQLException se) { System.exit(1);}

Page 25: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: BuildUserDB_Access.javatry { String dropString = "DROP TABLE " + tableName; stmt.executeUpdate(dropString);} catch (SQLException se) {} try { String createString = "CREATE TABLE " + tableName + " (username VARCHAR(128) NOT NULL PRIMARY KEY," + " password VARCHAR(128))"; stmt.executeUpdate(createString);

Page 26: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: BuildUserDB_Access.javaString insertString = "INSERT INTO " + tableName + " VALUES ('Scott McNealy', 'lavender')";stmt.executeUpdate(insertString);insertString = "INSERT INTO " + tableName + " VALUES ('Steve Jobs', 'aqua')";stmt.executeUpdate(insertString);insertString = "INSERT INTO " + tableName + " VALUES ('Bill Gates', 'blue')";stmt.executeUpdate(insertString);

Page 27: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Example: BuildUserDB_Access.java

ResultSet rset = stmt.executeQuery("SELECT * FROM " + tableName); while( rset.next() ) {

System.out.println(rset.getString("username") + ":" +

rset.getString("password")); } stmt.close(); rset.close(); conn.close(); } catch (SQLException se) {} }}

Page 28: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Thread

A sequential flow of control within a programAll programs have at least one threadIn Java, the thread is Application: main() Applet: Browser is main thread

Java is a multi-threaded language

Page 29: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Creating Threads in Java

Create an object of Thread by Subclass Thread Provide definition of run() method

Implement Runnable interface Declare run() method Create Thread object when needed

Page 30: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Subclassing the Thread Class

public class SimpleThread extends Thread {

…..

public void run() {

// provide an override for run() method

}

}

Page 31: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Implement Runnable Inteface

public class Test extends Applet implements Runnable{

private Thread testThread = null;

// when needed, create instance of Thread

testThread = new Thread(this, “Test”);

Page 32: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Two types of thread

Daemon thread• background thread subordinate to creator thread• ends when creator thread ends• threads that run indefinitely usually are created as

daemon threads

User thread• independent of creator thread• has life of its own!• run() method returns after done or it must be explicitly

stopped or destroyed

Page 33: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Threads and priority scheduling

Can run in parallel if there are multiple processors.

On a single CPU, threads are scheduled

Threads are scheduled based on priority relative to other threads

system chooses the runnable thread with highest priority; which runs until

it yields (to thread with same priority) or exits run() or is preempted

Page 34: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Thread Priority

Threads inherit priority from their creator can be modified afterwards MIN_PRIORITY (1) to MAX_PRIORITY (10) NORM_PRIORITY (5) is default

Page 35: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Time Slicing and Priority Scheduling

Time-slicing implemented by some OSs to fight selfish thread behavior each process gets a quantum of time, executes in a “round-robin”

fashion; i.e., each in turn

Priority Scheduling threads at same priority can share as above threads at lower priority must wait threads at higher priority preempt lower threads but lower priority thread may be run to avoid starvation

– up to the thread scheduler in JVM

Page 36: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Stopping ThreadsStop when the task is finished (a ‘natural’ death)thread arranges for own termination; run() method terminates ‘naturally’interrupt()

one thread signals another thread that it should stop just sets a flag; does not stop the thread

isInterrupted() checks to see if a thread has been interrupted (may still be running)

isAlive() checks to see if a thread is still operating if true, thread is started and not stopped; may be Runnable or Not

Runnable

Page 37: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Thread Synchronization

At times it is necessary to limit resources to one user at a time. use an internal lock to ensure only one thread

among competitors gains access to critical sections of code

A thread acquires the lock by executing: a synchronized instance method of that object. body of a synchronized statement that synchronizes on the

object. a synchronized static method of a class.

Page 38: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Synchronization at the Method level

synchronized public void method1() {...

//at the code block level

synchronized(theObject) statement

Page 39: Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled

Waiting for a Threadjoin() waits until thread dies; no synchronization used

thread1.join(); // waits until thread1 dies

thread1.join(1000); // wait up to 1 second

sleep(long millisec) suspend execution for specified time

can throw InterruptedException, so must be in try block or must indicate calling

method throws this exception