Your computer takes exceptio s s are errors i the logic of a program (ru-time errors). Examples: i thread mai java.io.filenotfoud: studet.txt (The system caot fid the file specified.) i thread mai java.lag.nullpoiter: at FileProcessor.mai(FileProcessor.java:9) 1 Questio: do all ru-time errors cause s? Causes of s The Class Most exceptios happe because of corer cases : your program does somethig at the boudaries of what Java kows how to hadle. For example: Java kows how to ope files for readig, mostly. But if you tell it to ope a file that does t exist, it does t kow how it should behave. It throws a exceptio, ad gives the programmer a opportuity to defie how the program should react. As with aythig i Java, is a class Method void pritstacktrace() Strig getlocalizedmessage() Strig tostrig() What it does Prits the seuece of method calls leadig up to the statemet that caused the. Returs a detail message. Returs the class ame ad detail message. The methods i the class ca be useful for debuggig, as we will see.
The class hierarchy (partial) Pitch ad catch Error Throwable Whe a Java statemet causes a (called throwig the ), by default Java abruptly eds the program. IO ClassNotFoud Rutime To stop this default behavior, you ca write code that catches the throw. EOF FileNotFoud UkowHost Arithmetic ClassCast IdexOut OfBouds NullPoiter Catch: A example // For Scaer class public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); while(iput.hasnextlie()) System.out.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the file 'studet.txt'."); try/catch sytax try <statemets that might cause a exceptio>; catch block is a exceptio hadler for oe type of exceptio. catch(<type1> e1) <statemets> catch(<typen> en) <statemets> try block idicates that the eclosed statemets have exceptio hadlers associated with them. The type of exceptio that the catch block hadles is idicated with a parameter. You ca have as may catch blocks for oe try block as you like. They must each hadle a differet type of exceptio.
Cotrol Flow with try/catch Catch: A example try <statemets that might cause a exceptio>; catch(<type1> e1) <statemets> catch(<typen> en) <statemets> <statemets after try/catch> If o exceptio occurs durig the try block: jump to statemets after all the catch blocks. If a exceptio occurs i the try block: jump to the first hadler for that type of exceptio. After the catch fiishes, jump to the statemet after all the catch blocks. // For Scaer class public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); while(iput.hasnextlie()) System.out.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the file 'studet.txt'."); fially Remember try <statemets that might cause a exceptio>; catch(<type1> e1) <statemets> catch(<typen> en) <statemets> fially <statemets i here are doe whether a exceptio occurred or ot> Whe a exceptio occurs you jump to the appropriate catch block you do ot ever jump back to the try block If you absolutely must complete the try block you eed to put it iside a loop
Example Strig fileame = ull; Scaer ifromfile = ull; try Scaer ifromkbd = ew Scaer(System.i); System.out.prit("Eter file ame> "); fileame = ifromkbd.extlie(); ifromfile = ew Scaer(ew File(fileame)); catch (FileNotFoud e) System.out.pritl("Error opeig file " + fileame); /* but the file might ot be ope */ Example Strig fileame = ull; Scaer ifromfile = ull; boolea successfulope=false; do try Scaer ifromkbd = ew Scaer(System.i); System.out.prit("Eter file ame> "); fileame = ifromkbd.extlie(); ifromfile = ew Scaer(ew File(fileame)); successfulope=true; catch (FileNotFoud e) System.out.pritl("Error opeig file " + fileame); while (!successfulope); /* if we get this far, the file is ope */ Stack Traces Displayig the stack trace ifo How do you kow what wet wrog? All exceptios have methods that retur iformatio about the cause of the : Method getlocalizedmessage() getstacktrace() pritstacktrace() Descriptio Returs a Strig cotaiig a descriptio of the error Returs a array of StackTraceElemet objects, each of which cotais ifo about where the error occurred Displays the Stack Trace o the cosole. // For Scaer class public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); while(iput.hasnextlie()) System.out.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the file 'studet.txt'."); System.out.pritl(exceptio.getLocalizedMessage()); exceptio.pritstacktrace();
Multiple catch blocks Multiple catch blocks // For Scaer class // For Scaer class public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); PritWriter pw = ew PritWriter(ew File( uoted.txt )); public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); PritWriter pw = ew PritWriter(ew File( uoted.txt )); while(iput.hasnextlie()) pw.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the file 'studet.txt'."); catch(io exceptio) System.out.pritl( Could ot write to file uoted.txt. ); while(iput.hasnextlie()) pw.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the iput file."); System.out.pritl(exceptio.getLocalizedMessage()); exceptio.pritstacktrace(); catch(io exceptio) System.out.pritl( Could ot write to file uoted.txt. ); Checked ad Uchecked s Checked ad Uchecked s s happe while the program is ruig For most kids of s, the compiler is happy to let the programmer make mistakes that could lead to a exceptio at rutime. Uchecked (by the compiler) s They are caused by programmer error. The compiler lets the programmer screw up. e.g., NullPoiter, IdexOutOfBouds s happe while the program is ruig For most kids of s, the compiler is happy to let the programmer make mistakes that could lead to a exceptio at rutime. But, for certai kids of exceptios, the compiler will check to see if your code might cause a exceptio at ru-time. Checked (by the compiler) s: They are caused by thigs outside of the programmer s cotrol (eg, a file does t exist). The compiler reuires that the programmer declare what to do if the occurs.
Checked ad Uchecked s Optios for Checked s Error Throwable If the compiler detects that a statemet might cause a Checked, it reuires the programmer to do either of the followig: IO ClassNotFoud Rutime 1. Catch the EOF FileNotFoud UkowHost Arithmetic ClassCast 2. Declare that crashig is acceptable Use the throws clause i the method sigature IdexOut OfBouds NullPoiter Otherwise, the program will ot compile. Throws: A example Catch or throw? // For Scaer class public static void mai(strig [] args) throws FileNotFoud File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); while(iput.hasnextlie()) System.out.pritl("> " + iput.extlie()); Whe should you catch a exceptio, ad whe should you declare that it ca be throw? Usually, if your catch block is ot goig to do aythig besides prit a error message ad uit the program, it s better to just throw the exceptio You should oly catch a exceptio if you re really goig to hadle the error so that it wo t affect the rest of the program.
Causig a ruckus Guess what you ca create your very ow s, ay time you wat! The throw keyword: (ote: NOT the same as the throws keyword!) Use it to make your code throw a exceptio throw ew (); Maily useful for passig messages betwee methods that are t easily doe with returs