05 Exception and Java IO
05 Exception and Java IO
05 Exception and Java IO
Lecture 5
Exception and Java I/O
CCS2304
Exceptions
2
Exceptions Types
3
System Errors
4
Exceptions
5
Runtime Exceptions
6
Checked Exceptions vs Unchecked Exceptions
7
Unchecked Exceptions
8
Unchecked Exceptions
• In most cases, unchecked exceptions reflect programming logic
errors that are not recoverable. For example,
9
Exceptions Hierarchy
Exception Types
11
The Catch or Specify Requirement
• Valid Java programming language code must honor the
Catch or Specify Requirement. This means that code that
might throw certain exceptions must been closed by
either of the following:
– A try statement that catches the exception. The try must
provide a handler for the exception.
– A method that specifies that it can throw the exception. The
method must provide a throws clause that lists the
exception.
12
Catch or Declare Checked Exceptions
• Java forces you to deal with checked exceptions. If a
method declares a checked exception (i.e., an exception
other than Error or RuntimeException), you must invoke
it in a try-catch block or declare to throw the exception
in the calling method.
14
The General Form of an Exception-Handling Block
try{ class Exc2 {
// block of code to monitor for errors public static void main(String args[]) {
} int d, a;
catch(ExceptionType1 exOb) { try { // monitor a block of code.
// exception handler for ExceptionType1 d = 0;
} a = 42 / d;
catch(ExceptionType2 exOb) { System.out.println("This will not be printed.");
// exception handler for ExceptionType2 }
} catch (ArithmeticException e) {
// ... System.out.println("Division by zero.");
finally{ }
// block of code to be executed before System.out.println("After catch statement.");
try block ends }
} }
15
Three Basic Rules for Exception-Handling
1- Multiple Catch Clauses void m(int i) {
int [] x = {1,4,0,2};
• After one catch statement executes, try {
the others are bypassed. int d = 4 / x[i]; }
• Exception subclasses must come before catch(ArrayIndexOutOfBoundsExceptione)
any of their superclasses, otherwise {//}
compile error. catch(ArithmeticExceptione)
{//}
2- Exception Propagation }
• If exception is not caught at its exact public static void main (String[] args) {
level , it propagates upwards towards ExcepDemo3 n = new ExcepDemo3();
the calling method. try {
• Exception can be caught at a higher n.m(3,0); }
level. catch(ArithmeticException e) {
//code to handle Exception}
}
}
void m(int x, int y) {
int z = x / y;
}
try {
System.out.println(refVar.toString());
}
catch (NullPointerExceptionex) {
System.out.println("refVaris null");
}
17
When do you use Exceptions
• It is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
18
Specifying the Exceptions Thrown by a Method
19
Example: Handling The Exceptions from
method Integer.parseInt
Class Integer
public static int parseInt(String s) throws NumberFormatException
Parses the string argument as a signed decimal integer.
Throws: NumberFormatException. If the string does not contain a parsable
integer
Unchecked
Exception
Optional
try-catch
20
Creating Object of scanner to read data from a file
public Scanner(File source) throws FileNotFoundException
Constructs a new Scanner. That produces values scanned from the specified file.
Parameters:
source - A file to be scanned
Throws:
FileNotFoundException – if source is not found.
Mandatory
try-catch
checked
Exception
22
Throwing Exceptions
• When the program detects an error, the program can
create an instance of an appropriate exception type and
throw it. This is known as throwing an exception.
• Here is an example,
23
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius) throws
IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
24
Throwing Exceptions Example
class Student {
private double GPA;
public void setGPA (double GPA) {
if (GPA > 4)
throw new IllegalArgumentException();
this.GPA = GPA;
} class Student {
} private double GPA;
public void setGPA (double GPA) throws Exception {
if (GPA > 4)
throw new Exception();
this.GPA = GPA;
}
}
25
Declaring your own exceptions
class myException extends RuntimeException { import java.io.IOException
class myException extends I0Exception {
Unchecked Checked
Exception Exception
} }
Example
26
Using Finally
• For each try-catch block there can be only one finally block.
• Case 1: If an exception is thrown with a matching catch block, then the
finally block is executed after the catch block and program continues.
• Case 2: If an exception does not happen the finally block will be
executed and program continues.
• Case 3: if an exception is thrown but not caught then the finally block
will be executed after the try block , then program stops.
try {
// statement 1 Case 1: statement 1 – statement 2 – statement 3 – statement 4
}
// statement 4
27
Java I/O Processing
28
Class File
• The File class in the java.io package represents
files.
– Create a File object to get information about a file on the
disk. (Creating a File object doesn't create a new file on your
disk)
File f = new File ("example.txt");
if (f.exists() && f.length() > 1000) {
f.delete();
}
29
The File Class
• To operate on a file, we must first create a File object
(from java.io.File).
30
Some File Methods
31
Class Scanner
• To read a file, create a File object and pass it as a parameter when
constructing a Scanner.
File f = new File("numbers.txt");
Scanner input = new Scanner(f);
32
Input Tokens
• token: A unit of user input. Tokens are separated by whitespace (spaces,
tabs, new lines).
• Example: If an input file contains the following:
23 3.14
John Smith
• The tokens in the input are the following, and can be interpreted as the
given types:
Token Type(s)
23 int, double, String
3.14 double, String
John String
Smith String
• Each call to next, nextInt, nextDouble, etc. advances the cursor to the
end of the current token, skipping over any whitespace.
33
Reading Data using Class Scanner
• A Scanner breaks its input into tokens using whitespace. (spaces,
tabs, new lines).
• The resulting tokens may then be converted into values of
different types using the various methods.
35
Example
36
public float nextFloat()
• Scans the next token of the input as a float .
• This method will throw InputMismatchException if the next token
cannot be translated into a valid float value.
• If the translation is successful, the scanner advances past the
input that matched.
• If the next token matches the Float regular expression defined
above, then the token is converted into a float value.
Throws:
InputMismatchException – if the next token does not match the Float
regular expression, or is out of range
NoSuchElementException – if input is exhausted
IllegalStateException – if this scanner is closed
37
Testing Before Reading
• The preceding program is impractical because it only processes
exactly 5 values from the input file.
– Typically, the actual program would read the entire file,
regardless of how many values it contains.
• Reminder: The Scanner has useful methods for testing to see
what the next input token will be:
38
Example
39
Example
40
Example: Reading Data From File
41
Case Study
42
Case Study
43
Writing Data Using PrintWriter
• First, you have to create a PrintWriter object for a text file as
follows:
– PrintWriter output = new PrintWriter(filename);
44
Any Questions?
45
What is an Exception
• An exception is an unwanted or unexpected event, which occurs
during the execution of a program (i.e., at run time), that
disrupts the normal flow of the program’s instructions.
• Error vs Exception
Errors Exception
Represent serious and usually Exception indicates conditions
irrecoverable conditions like that a reasonable application
library incompatibility, infinite might try to catch.
recursion, or memory leaks.
- Exceptions are the problems
- Errors are generated to indicate which can occur at runtime and
errors generated by the runtime compile time. It mainly occurs in
environment. the code written by the
developers.
- Ex: JVM is out of memory.
Normally, programs cannot
recover from errors.
46
What is an Exception
• An exception can occur for many different reasons:
– A user has entered an invalid data.
– A file that needs to be opened cannot be found.
– A network connection has been lost in the middle of
communications.
47
Exception
48
Exception Solving
49
Exception
50
Exception Solving
51
Exception
52
Exception Execution
53
Exception Execution
54
Exception Multicatch
55
Unknown Exception
Arrangement is important
56
Finally Block
• A finally block in Java can be used to put “cleanup” code
such as closing a file, closing connection, etc.
• Rule: for each try block there can be one or more catch
blocks, but only one finally block.
57
Finally Block
58
Finally Block
N.B: The finally block will not be executed if the program exits
(either by calling System.exit() or by causing a fatal error that
causes the process to abort.
59
Exception Handling
• There are three main categories of exceptional conditions:
– Checked exceptions (Compile-time exceptions)
– Unchecked exceptions (Runtime exceptions)
– Errors
61
Java.lang Package from API Documentation
62
Difference Between Exception and Error
• Error and Exception both are subclasses of the java Throwable
class that belongs to java.lang package.
63
Exception (FileNotFoundException)
64
Exception (Read File Contents)
66
Exception (Try-with-resources) (after v1.7)
67
Exception (Throws)
2
Exception Propagation
(Exception propagators)
68
Exception (Throws)
Any method will call readFile method
should handle the throws exceptions
either by try-catch or using throws
69
Error
Recursion error
But we don’t figure out the problem yet
70
throw keyword
• The “throw” keyword is used to create a custom exception or
error.
71
throw keyword
Custom Exception
72
throw keyword
73
throw keyword
74
Throw Vs Throws
throw throws
75
Exceptions
76
User-Defined Exception
checked Exception
Unchecked
Exception
77