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 fairly rare and usually fatal. They
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 reading
or writing, but not reading and writing. - Random access I/O supports reading and writing
data at any positions of a file. A random access
file may be opened for 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
9Reading/Writing Text Files
- Use reader and and writer classes for text I/O.
Handles 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"
)))
10Example 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))
11Example 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()
12Example 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
()
13Example Inventory.java
for (int scan 0 scan System.out.println(itemsscan) catch
(FileNotFoundException exception)
System.out.println("The file " file
" was not found.") catch
(IOException exception)
System.out.println(exception)
14Example 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
15Example 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 line) for (int num1 num value (int) (Math.random() 100)
outFile.print(value " ")
outFile.println() outFile.close()
16Example 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
17JDBC
- 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
18Example 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
19Example 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)
20Example 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)
21Example 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)
22Example 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)
23The UserPass Table