1 / 39

Exceptions

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. Exception Hierarchy. Errors:

erek
Télécharger la présentation

Exceptions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 by another part of the program

  2. Exception Hierarchy • Errors: • 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.

  3. 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 }

  4. Define Your Own Exception public class MyException extends Exception {   public MyException(String msg) {     super(msg);   } }

  5. Throw Statement and Throws Clause public class MyClass {   public void aMethod(int i, int j)     throws MyException {     // ...     throw new MyException(reason);     // ...   } }

  6. 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 stream • An I/O stream is either a • character stream, which deals with text data • byte stream, which deal with binary data

  7. 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.

  8. Standard I/O Streams • There are three standard I/O streams: • standard input – System.in • standard output – System.out • standard error – System.err

  9. Some classes used for I/O

  10. Common Text Input Combinations

  11. I/O Program Examples ReadCharacters.java ReadLines.java ReadWords.java

  12. Reading/Writing Text Files • The reader and writer classes can handle text I/O. Handle conversion between Unicode and native character encoding • May throw IOException BufferedReader in    = new BufferedReader(        new FileReader("foo.in")); PrintWriter out    = new PrintWriter(        new BufferedWriter(          new FileWriter("foo.out")));

  13. 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)); } }

  14. Example: Inventory.java import 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();

  15. Example: Inventory.java while (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();

  16. 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); } } }

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

  18. Example: TestData.java final 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();

  19. Example: TestData Output 12 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

  20. JDBC • Java Database Connectivity • Steps: 1. Load a JDBC driver 2. Establish a connection with a data base 3. Send queries and update statements 4. Process the results

  21. Setting up an Access Database Driver for Windows • Open the “ODBC Data Sources (32 bit)” folder Start|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 box • Click “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 Dialog • The 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.

  22. username password Bill Gates blue Scott McNealy lavender Steve Jobs aqua The UserPass Table

  23. Example: BuildUserDB_Access.java import 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;

  24. Example: BuildUserDB_Access.java try { 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); }

  25. Example: BuildUserDB_Access.java try { 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);

  26. Example: BuildUserDB_Access.java String 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);

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

  28. Thread • A sequential flow of control within a program • All programs have at least one thread • In Java, the thread is • Application: main() • Applet: Browser is main thread • Java is a multi-threaded language

  29. 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

  30. Subclassing the Thread Class public class SimpleThread extends Thread { ….. public void run() { // provide an override for run() method } }

  31. 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”);

  32. 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

  33. 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

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

  35. Time Slicing and Priority Scheduling • Time-slicing • implemented by some OSs to fight selfish threadbehavior • 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

  36. Stopping Threads • Stop 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 Runnableor Not Runnable

  37. 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 sectionsof 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.

  38. Synchronization at the Method level synchronized public void method1() {... //at the code block level synchronized(theObject) statement

  39. Waiting for a Thread • join() • 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

More Related