|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Declaring Checked Exceptions
A method signature can end with a throws clause followed by one or more exception types that the method can throw. A 'checked exception' is an exception that is derived from the class (or is in fact an instance of) Exception. A checked exception is not mandatory but should be declared in a method signature in the following cases:: - The 'throw' keyword is used to throw the exception in the method. - Another method that throws the specific exception is called within the current method and the try / catch statements are not used. If a method throws more than one exception the exception names are separated by commas. An unchecked exception is derived from the class 'Error'. Both the Exception and Error classes are derived from the super class 'Throwable'. Here are a couple of examples of how to use the throws clause in a method: |
public void createFile() throws IOException { //The creation of the FileWriter object may throw an //IOException, so it must either by caught through try / catch //statements or add a throws clause to the method signature, //else the compiler will complain. BufferedWriter writer = new BufferedWriter(new FileWriter("javadb.com.txt")); } public void convertStringToInt() throws NumberFormatException { //In this case the compiler will not complain if we don't add a throws //clause to the method signature or use the try / catch statements. //However if the conversion fails (for example if the variable s has //the value "123f") a NumberFormatException will be thrown and we can //use the throws clause to throw the exception to the caller. String s = "123"; int number = Integer.parseInt(s); } |
| Previous | Next | |
Tutorial Home | ||
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
