CS203 Java Object Oriented Programming Errors and Exception Handling.
-
Upload
ross-greene -
Category
Documents
-
view
233 -
download
0
Transcript of CS203 Java Object Oriented Programming Errors and Exception Handling.
![Page 1: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/1.jpg)
CS203 Java Object Oriented ProgrammingErrors and Exception Handling
![Page 2: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/2.jpg)
Examples of Exceptions
ArrayIndexOutOfBoundException
NumberFormatException
int a[] = new int[10];for( int i=0 ; i <= a.length ; ++i ) a[i] = i;
String s = “7.3”;int n = Integer.parseInt( s );
![Page 3: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/3.jpg)
Runtime Errors
Errors happened when the program is running, e.g. Access an element outside array
boundary Read a file which doesn’t exist User input errors
Runtime error handling Error codes Exceptions
![Page 4: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/4.jpg)
Exception Types
![Page 5: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/5.jpg)
System Errors
System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
![Page 6: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/6.jpg)
Exceptions
Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
![Page 7: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/7.jpg)
Runtime Exceptions
RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
![Page 8: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/8.jpg)
Checked Exceptions vs. Unchecked Exceptions
RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.
![Page 9: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/9.jpg)
Unchecked ExceptionsIn most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions.
![Page 10: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/10.jpg)
Checked or Unchecked Exceptions
Unchecked exception.
![Page 11: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/11.jpg)
Error Codes
// n >= 1
int factorial( int n ){ // return an error code if( n < 1 ) return –1;
int fact = 1; for( int i=1 ; i <= n ; ++i ) fact *= i;
return fact;}
int f = factorial(x);
if( f == -1 ) // error handling{ System.err.println( “error!”); System.exit(1);}else // regular code{ // do something with f}
![Page 12: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/12.jpg)
Raise An Exception – throw
int factorial( int n ) throws LessThanOneException{ if( n < 1 ) throw new LessThanOneException();
int fact = 1; for( int i=1 ; i <= n ; ++i ) fact *= i; return fact;}
![Page 13: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/13.jpg)
A Closer Look at Throw
int factorial( int n ) throws LessThanOneException{ if( n < 1 ) throw new LessThanOneException();
int fact = 1; for( int i=1 ; i <= n ; ++i ) fact *= i; return fact;}
Return type
Returned value
Exception type
Exception value
![Page 14: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/14.jpg)
Exception Class
Pre-defined in JavaAll exception classes must inherit from this classImportant methods Exception() Exception( String msg ) String getMessage() void printStackTrace()
![Page 15: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/15.jpg)
Create An Exception Class
public class LessThanOneException extends Exception {
public LessThanOneException() { super(); }
public LessThanOneException( String msg ) { super(msg); }
}
![Page 16: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/16.jpg)
Handle An Exception – try and catch
try // regular code{ int f = factorial(n); // do something with f}catch( LessThanOneException e ) // error handling{ System.err.println( “error!” ); System.exit(1);}
![Page 17: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/17.jpg)
Using Exceptions
In a method where an error may occur Declare exception type in method header:
throws Raise an exception if the error occurs: throw
In the calling method Handle the exception
Enclose regular code in a try block Enclose error handling code in a catch block
Do not handle the exception Declare the exception in method header
![Page 18: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/18.jpg)
Throw Multiple Exceptions
public void foo() throws ExceptionA, ExceptionB, ExceptionC{ … throw new ExceptionA(“Bad thing A”);
… throw new ExceptionB(“Bad Thing B”);
… throw new ExceptionC(“Bad Thing C”);}
![Page 19: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/19.jpg)
Catch Multiple Exceptions
Or, if we don’t need to distinguish exactly which type of exception occurs
try{ foo();}catch( ExceptionA ea ){ // do something}catch( ExceptionB eb ){ // do something}catch( ExceptionC ec ){ // do something}
try{ foo();}catch( Exception e ){ System.err.println( e.getMessage() ); System.exit(1);}
![Page 20: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/20.jpg)
A More Complex Example
readFile {open the file;determine its size;allocate that much memory;read the file into memory;close the file;
}
![Page 21: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/21.jpg)
Handling Errors with Error Code
errorCodeType readFile { errorCode = 0; open the file; If (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode;}
![Page 22: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/22.jpg)
Handling Errors with Exceptions
readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch(fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; }}
![Page 23: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/23.jpg)
Advantages of Exceptions
Separate error handling code with from regular codePropagate errors up the call stackGroup error types and error differentiation
![Page 24: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/24.jpg)
Error Propagation Example
method1 {try { call method2; }catch (exception) { doErrorProcessing; }
}
method2 throws exception { call method3; }
method3 throws exception { call readFile; }
![Page 25: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/25.jpg)
Error Grouping and Differentiation Example
![Page 26: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/26.jpg)
The finally Clausetry { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }
![Page 27: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/27.jpg)
Cautions When Using ExceptionsException handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.
![Page 28: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/28.jpg)
When to Throw ExceptionsAn exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.
![Page 29: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/29.jpg)
When to Use ExceptionsWhen should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
![Page 30: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/30.jpg)
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
![Page 31: CS203 Java Object Oriented Programming Errors and Exception Handling.](https://reader035.fdocuments.in/reader035/viewer/2022062309/56649e045503460f94aefc11/html5/thumbnails/31.jpg)
Creating Custom Exception Classes
Use the exception classes in the API whenever possible.
Create custom exception classes if the predefined classes are not sufficient.
Declare custom exception classes by extending Exception or a subclass of Exception.