230 likes | 373 Views
Exceptions Lesson - 7. CSM-Java Programming-I Spring,2005. Objectives Review of last class Throwing Exceptions Exception Types When to use Exceptions throw throws try, catch and finally Wrapper Classes. CSM-Java Programming-I Lesson-1. Exceptions.
E N D
Exceptions Lesson - 7 CSM-Java Programming-I Spring,2005
Objectives • Review of last class • Throwing Exceptions • Exception Types • When to use Exceptions • throw • throws • try, catch and finally • Wrapper Classes CSM-Java Programming-I Lesson-1
Exceptions • A Java exception is an object that describes an error condition occurred in the code. • When an exception occurs, an object representing that exception is created and thrown in the method that caused the exception. That method may choose to handle the exception itself, or pass it on. • At some point, the exception is caught and processed. CSM-Java Programming-I Lesson-1
Throwing Exceptions • To signal an exceptional condition, use the throw statement to throw an exception object. public class BankAccount { public void withdraw(double amout) { if (amount > balance) { IllegalArgumentException ex = new IllegalArgumentException ( Amount exceeds balance”); throw ex; } balance = balance – amount; } } CSM-Java Programming-I Lesson-1
Throwing Exceptions • When an exception is thrown, the current method terminates immediately. • Throw exceptions only in exceptional cases. • Example1: When reading a line of input, do not throw an exception because end of line is reached. That is a normal condition, not an exceptional one. • Example2: Don’t throw an exception just to exit a deeply nested loop or a set of recursive method calls. CSM-Java Programming-I Lesson-1
Exception Types • All exception types are subclasses of class Throwable. • The two subclasses of Throwable are Error and Exception. • There are two types of exceptions in class Exception: • Checked exceptions – When you call a method that throws a checked exception, you must tell the compiler what you are going to do about the exception if it is ever thrown. • Unchecked exceptions – The compiler does not require you to keep track of unchecked exceptions. CSM-Java Programming-I Lesson-1
Exception Types • A subclass of Exception is RuntimeException. • Exceptions belonging to the subclasses of RuntimeException are unchecked expections. • All other subclasses of the class Exception are checked. • Exceptions of the type Error are caused by Java run-time environment • OutofMemoryError is an example of type Error. CSM-Java Programming-I Lesson-1
Exception Types • Checked exceptions are due to external circumstances that the programmer cannot prevent. The compiler checks that your program handles these exceptions. • Unchecked exceptions are programmers’ fault. CSM-Java Programming-I Lesson-1
Exceptions Hierarchy Throwable Error Exception Runtime Exception ClassNotFound Exception CloneNotSupproted Exception IOException Arithmethic Exception FileNotFound Exception CSM-Java Programming-I Lesson-1
throws • Majority of the checked exceptions occur when dealing with input and output. • Add a throws specifier to a method that can throw a checked exception. Eg: public void read(BufferedReader in ) throws IOException, ClassNotFoundException • Multiple exceptions can be separated by commas. CSM-Java Programming-I Lesson-1
Designing User Exception Types • If none of the standard types describes your particular error condition well enough, then design your own exception class. public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() { } public InsufficientFundsException(String reason) { super(reason); } CSM-Java Programming-I Lesson-1
Catching Exceptions • Every exception should be handled somewhere in your program. • If an exception has no handler, an error message is printed, and your program terminates. • In a method that is ready to handle a particular exception type, place the statements that can cause the exception inside a try block, and the handler inside a catch clause. CSM-Java Programming-I Lesson-1
Example: try, catch try { System.out.println(“What is your name?”); String name = console.readLine(); System.out.println(“Hello. “ + name + “!”); } catch(IOException ex) { ex.printStackTrace(); // should handle exception System.exit(1); } CSM-Java Programming-I Lesson-1
finally Clause • The finally construct is used to handle a situation in which some action has to be taken whether or not an exception is thrown. BufferedReader in= null; try { in = new BufferedReader(new FileReader(filename)); purse.read(in); } finally { if (in != null) in.close(); } CSM-Java Programming-I Lesson-1
finally Clause • Use the finally clause whenever you need to do cleanup, such as closing a file, so that cleanup occurs no matter how the method exits. • It is possible to have a finally clause following one or more catch clauses. • The code in the finally block is executed whenever the try block is exited through any of the next three ways. CSM-Java Programming-I Lesson-1
finally Clause • After completing the last statement of try block. • When an exception was thrown in the try block that is being passed to this method’s caller. • When an exception was thrown in the try block that was handled by one of the catch clauses. CSM-Java Programming-I Lesson-1
Wrapper Classes • A wrapper class is a class that encapsulates a single, immutable value. • All the wrapper classes can be constructed by passing the value to be wrapped into the appropriate constructor. • The values wrapped inside two wrappers of the same type can be checked for equality by using the equals() method. • Wrapper classes are useful whenever it would be convenient to treat primitive data as if it were an object. CSM-Java Programming-I Lesson-1
Wrapper Classes • The abstract class Number is the superclass that is implemented by the classes that wrap the numeric types byte, short, int, long, float and double. • Number has abstract methods that return the value of the object in each of the different number formats. Eg: doubleValue(), floatValue(). • The concrete subclasses that hold explicit values of each numeric type are: Double, Float, Byte, Short, Integer, Long. CSM-Java Programming-I Lesson-1
Wrapper Classes • The constructors of the Double wrapper class are: Eg: Double(double num) Double(String str) throws NumberFormatException string containing a double value or a sting containing a float-point value. • NumberFormatException:Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format. CSM-Java Programming-I Lesson-1
Wrapper Classes • The constructors of the Byte, Short, Integer and Long are: Byte(byte num) Byte(String str) throws NumberFormatException Short(short num) Short(String str) throws NumberFormatException Integer(int num) Integer(String str) throws NumberFormatException Long(long num) Long(String str) throws NumberFormatException CSM-Java Programming-I Lesson-1
Wrapper Class Methods • isInfinite() - Returns true if this Double value is infinitely large in magnitude, false otherwise. • isNaN() - Returns true if this Double value is a Not-a-Number (NaN), false otherwise. • The Byte, Short, Integer, Long classes provide the parseByte(), parseShort(), parseInt() and parseLong() methods, to return the byte, short, int, long equivalent of the numeric string with which they are called. Eg: int i = Integer.parseInt(str); CSM-Java Programming-I Lesson-1
Wrapper Class Methods • The Byte, Short, Integer, Long classes provide the toString() method to convert a number to a string. • The Integer and Long classes provide the toBinaryString(), toHexString(), and toOctalString() to convert a value into a binary, hexadecimal or octal string. CSM-Java Programming-I Lesson-1
Wrapper Class Methods • Character has the constructor Character(char ch) and wraps a character. • The charValue() method returns the char value contained in a Character object. • Boolean is a wrapper around boolean values. Boolean defines the constructors: • Boolen(boolean boolValue) • Boolean(String boolString) CSM-Java Programming-I Lesson-1