Exception: an error, an unusual happening.
Examples
Chart showing who is in charge of who (NOT inheritance) Each person is a 'method' which invokes other methods to get work done. MD Manager1 Manager2 Chief technician technician1 technician2 etc...Possible problems
Imagine that the person who creatd the company structure (e.g a management consultant) wants to specify - in advance -
Possibilities for the 'paper' error
a b c d e f g e.g a calls b and c c calls d and e e might be a complex package, split down into f, g internally. we may not have it source code - we simply call e to make it work.What happens if we get an error in a low-level method - e.g e ?
doA(); doB(); doC();now we add erro-handling, with IF:
doA(); if(doA went wrong) handle doA error else doB(); if(doB went wrong) handle doB error else doC(); if(doC went wrong) handle doC error....here, the error-handling logic dominates, even though errors don't happen often!
try { doA(); doB(); doC(); } catch ( ){ handle errors... eg an error message }we surround any code that might produce an error with try {...}
Example: reading data from a file. Eventually, we are bound to reach the end of the file. This is NOT an exception.
If c throws an exception, c might catch it locally.
But if there is no appropriate catch in c, Java looks in b,
then in a,
for a matching catch.
it is checked, so must catch it locally, or pass it up to the calling method. So either handle it locally:
private void openPayroll(...) { try{ openFile("data.txt"...); //approx java - possible exception in here } catch (FileNotFoundException...){ // maybe display an error message... } }or state that you will throw it up to the caller:
private void openPayroll(...) throws FileNotFoundException{ openFile("data.txt"...); } omitting the throws will produce a compilation error.
NumberFormatException
ArrayIndexOutOfBounds
e.g:
int a[] = new int[10]; // 0 to 9 for(int n=0; n <=10; n++){ a[n]=0; //error when n is 10 }
Drawing package Beta 2 Array element in 'a' too big in method fred. (it is 10, and 9 is the maximum.) Contact MSc software immediately!