Exception Handling in Java
Activity Outcomes:
- Describe the notation of exception handling
- React correctly when certain exceptions occur
- Use Java’s exception-handling facilities effectively in classes and programs
Lab Activities:
Activity 1:
Java program that extends java Exception class.
Solution:
Activity 2:
NOTE: If Super class method throws an exception, then Subclass overriden method can throw the same exception or no exception, but must not throw parent exception of the exception thrown by Super class method.
It means, if Super class method throws object of NullPointerException class, then Subclass method can either throw same exception, or can throw no exception, but it can never throw object of Exception class (parent of NullPointerException class). Subclass overridden method with exception.
Solution:
Activity 3:
Subclass overridden method with no exception.
Solution:
Activity 4:
Subclass overridden method with parent Exception.
Solution:
Activity 5:
Using ObjectInputStream to Read from a File
Solution:
Home Activities:
Activity 1:
Write java code to create an input stream of type ObjectInputStream that is named from File and is connected to a file named stuff.data.
Activity 2:
Write a Java program that asks the user for the name of a binary file and writes the first data item in that file to the screen. Assume that the first data item is a string that was written to the file with method WriteUTF.
Activity 3:
Write a complete Java program that asks the user for a file name, tests whether the file exists, and if the file does exist, ask the user whether or not it should be deleted and then does as the user requests.