Title: Exceptions
 1Exceptions
- 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
2Exception 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.
3Exception 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   
 4Define Your Own Exception
public class MyException extends Exception  
  public MyException(String msg)      
 super(msg)      
 5Throw Statement and Throws Clause 
public class MyClass    public void 
aMethod(int i, int j)     throws MyException 
     // ...     throw new MyException(reason) 
    // ...     
 6I/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 
7Two 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.
8Standard I/O Streams
- There are three standard I/O streams 
- standard input  System.in 
- standard output  System.out 
- standard error  System.err
9Some classes used for I/O 
 10Common Text Input Combinations 
 11I/O Program Examples
- ReadCharacters.java 
- ReadLines.java 
- ReadWords.java 
12Reading/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"
)))  
 13Example 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))   
 14Example 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 
InventoryItemMAX 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() 
 15Example Inventory.java
while (line ! null)  tokenizer  new 
StringTokenizer (line) name  
tokenizer.nextToken() try  units  
Integer.parseInt(tokenizer.nextToken()) 
price  Float.parseFloat(tokenizer.nextToken()) 
 itemscount  new InventoryItem(name,
 units, price)  catch (NumberFormatException 
exception)  System.out.println("Error in 
input. Line ignored") System.out.println(lin
e)  line  inFile.readLine()  inFile.close
() 
 16Example Inventory.java
 for (int scan  0 scan lt count scan) 
 System.out.println(itemsscan)  catch 
(FileNotFoundException exception)  
System.out.println("The file "  file  
 " was not found.")  catch 
(IOException exception)  
System.out.println(exception)    
 17Example 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 
 18Example 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 line1 line lt MAX 
line)  for (int num1 num lt MAX num)  
 value  (int) (Math.random()  100) 
outFile.print(value  " ")  
outFile.println()  outFile.close() 
 19Example 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 
 20JDBC 
- 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 
21Setting up an Access Database Driver for Windows 
- Open the ODBC Data Sources (32 bit) folder 
- StartSettingsControl PanelODBC 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.
22The UserPass Table 
 23Example 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  
"jdbcodbc" public static void main(String 
args)  String dbName  "Users" 
String tableName  "UserPass" Connection 
conn  null Statement stmt  null 
 24Example BuildUserDB_Access.java
try  Class.forName(jdbcDriver)  
catch(ClassNotFoundException e)  
System.exit(1)  try  String url  
dataSource  dbName conn  DriverManager.getCon
nection(url) stmt  conn.createStatement()  
catch (SQLException se)  System.exit(1)  
 25Example 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) 
 26Example BuildUserDB_Access.java
String insertString  "INSERT INTO "  
tableName  " VALUES ('Scott McNealy', 
'lavender')" stmt.executeUpdate(insertString) in
sertString  "INSERT INTO "  tableName  " 
VALUES ('Steve Jobs', 'aqua')" stmt.executeUpdate
(insertString) insertString  "INSERT INTO "  
tableName  " VALUES ('Bill Gates', 
'blue')" stmt.executeUpdate(insertString) 
 27Example BuildUserDB_Access.java
 ResultSet rset  
stmt.executeQuery("SELECT  FROM "  tableName) 
 while( rset.next() )  System.out.println(rs
et.getString("username")  
 ""  rset.getString("password")) 
  stmt.close() rset.close() 
 conn.close()  catch (SQLException se)    
 28Thread 
- 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 
29Creating 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 
30Subclassing the Thread Class 
- public class SimpleThread extends Thread  
- .. 
-  public void run()  
-  // provide an override for run() method 
-   
31Implement Runnable Inteface
- public class Test extends Applet implements 
 Runnable
- private Thread testThread  null 
-  
-  // when needed, create instance of Thread 
-  testThread  new Thread(this, Test) 
32Two 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
33Threads 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
34Thread Priority 
- Threads inherit priority from their creator 
- can be modified afterwards 
- MIN_PRIORITY (1) to MAX_PRIORITY (10) 
- NORM_PRIORITY (5) is default 
35Time 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
36Stopping 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 Runnable or Not Runnable
37Thread 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.
38Synchronization at the Method level
- synchronized public void method1() ... 
-  // at the code block level 
-  synchronized(theObject) statement 
-  
-  
39Waiting 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