Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Which Exceptions Are You REQUIRED To Check For In Your Programs? There are exceptions that are not derived from Error or RuntimeException which are checked exceptions. You must handle a checked exception, or there must be a throws clause listed in the method header that informs the compiler what exceptions can be thrown from a method. RuntimeException serves as a superclass for exceptions that result from programming errors – the incorrect use of the Java API. For example a NullPointerException occurs when a method tries to access a member of an object through a null reference. These exceptions can be avoided with properly written code. Exceptions derived from the Error class are thrown when a critical error occurs, and SHOULD NOT be handled. For example, consider Virtual Machine Errors such as OutOfMemoryError and StackOverFlowError which indicate the JVM is can’t continue operating. You MUST handle or throw these Exceptions. throws Clause If you include a method that throws an exception but you have not “caught” the exception, you must include a throws clause. The keyword throws is written at the end of the method header, followed by a list of the types of exceptions that the method can throw. public Date readDate(String fileName) throws IOException,ClassNotFoundException The throws clause must be included at the end of the method header for all of the methods in the call stack until the exception has been “caught.” import java.io.*; import java.util.Scanner; public class ExceptionDemo { public static void main(String [] args) throws FileNotFoundException { displayFile("data.txt"); } public static void displayFile(String name) throws FileNotFoundException { File file = new File(name); Scanner input = new Scanner(file); // may throw a FileNotFoundException String msg; while(input.hasNext()) { msg = input.nextLine(); System.out.println(msg); } input.close(); } } Throwing Exceptions You can write code that explicitly throws one of the standard Java exceptions, or an instance of a custom exception that you have designed. The throw statement is used to manually throw an exception and should not be confused with the throws clause that may appear at the end of a method header. The throw statement causes an exception object to be created and thrown. throw new ExceptionType(MessageString); For example, you may throw an exception when a user enters a wrong login ID or password. import java.io.*; import java.util.Scanner; public class ExceptionDemo { public static void main(String [] args) { String password; Scanner keyboard = new Scanner(System.in); boolean valid; //loop until a valid password will be entered do { valid = true; //Assume password will be true try { System.out.println("Enter Password: "); password = keyboard.nextLine(); checkValid(password); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); valid = false; } }while (!valid); } public static void checkValid(String str) throws IllegalArgumentException { if (str.length() < 6) throw new IllegalArgumentException("Password must be 6 characters"); } } 1. The throw statement causes termination of the normal flow of control of the java code and stops the execution of the subsequent statements. 2. The throw clause transfers the control to the nearest catch block handling the type of exception object throws. 3. If no such catch block exists, the program terminates. The throw statement accepts a single argument, which is an object of the Exception class Why have different Exception Classes? Why not have just Throwable or Error and Exception classes? If you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's. Do you need an exception type that isn't represented by those in the Java platform? Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors? Does your code throw more than one related exception? If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained? You must extend the Exception class or one of its derived classes. //Create your own Exception public class NegativeStartingBalance extends Exception { public NegativeStartingBalance (double amount) { super("Error: Negative stating Balance: "+ amount); } } //Throwing an Exception public class BankAccount { private double balance; public BankAccount(double startingBalance) throws NegativeStartingBalance { if (startBalance < 0) throw new NegativeStartingBalance(startBalance); else balance = startBalance; } } //Catching an Exception public class BankDemo { public static void main(String [] args) { Scanner keyboard = new Scanner(System.in); double amount; boolean valid = true; BankAccount account; //Loop until a valid account has been created. do { System.out.println("Enter a beginning balance: "); amount = keyboard.nextDouble(); try { account = new BankAccount(amount); } catch (NegativeStartingBalance e) { valid=false; System.out.println(e.getMessage()); //calls Throwable getMessage method System.out.println("Please enter a positive value. "); } } while (!valid); } } Advantage of Exceptions: Separating Error-Handling Code from "Regular" Code Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. For example, consider the pseudocode method here that reads an entire file into memory. readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } At first glance, this function seems simple enough, but it ignores all the following potential errors. What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed? To handle such cases, the readFile function must have more code to do error detection, reporting, and handling. Here is an example of what the function might look like. errorCodeType readFile { initialize errorCode = 0; } Exceptions enable you to write the main flow of open the file; your code and to deal with the exceptional cases if (theFileIsOpen) { determine the length of the file; elsewhere. If the readFile function used if (gotTheFileLength) { exceptions instead of traditional errorallocate that much memory; management techniques, it would look more like if (gotEnoughMemory) { the following. read the file into memory; if (readFailed) { readFile { errorCode = -1; try { } open the file; } else { determine its size; errorCode = -2; allocate that much memory; } read the file into memory; } else { close the file; errorCode = -3; } catch (fileOpenFailed) { } doSomething; close the file; } catch (sizeDeterminationFailed) { if (theFileDidntClose && errorCode == 0) { doSomething; errorCode = -4; } catch (memoryAllocationFailed) { } else { doSomething; errorCode = errorCode and -4; } catch (readFailed) { } doSomething; } else { } catch (fileCloseFailed) { errorCode = -5; doSomething; } } return errorCode; } Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively.