In this lab, we are going to talk about exception handling, and how we could implement our exception that could be later be handled, then we will talk about text files operations.
As you might know, an exception is a runtime error, by handling it, we could take an action if it occurs, this action could be a fixable problem, or you could at least inform the user of it.
we could use a try-catch block to handle an exception, for example:
Notice that the division operation could fail if n2 = 0
, so if we put the statements inside the try-catch block, the try block will run, if an exception occurs, the program will execute the catch block, with a parameter that has the type Throwable
or any subtype of it.
You could have more than one catch block, and each catch will have a different type of argument.
The order of the catch blocks is important, you should never put a subclass under its superclass, as the later catch block will never be executed.
You could define your exception, this exception will indicate that you can't complete a certain operation, then you can create a new instance of this exception and throw it back.
Notice that we added throws to getPost
method, which indicates that this method will throw this type of exception.
An Exception that extends the Exception
class must be thrown or caught, but extending RuntimeException
makes your exception unchecked.
The finally block could be added to the try-catch block, which will be executed if an error occurs or not.
This is very useful for cleaning up operations, such as closing a file.
Important Note: don't use exceptions for expected errors, check them with an if will make your code much better!
As we have already covered simple text operations, this section should be an easy section for you!
The file is a class that implements different methods to manipulate files and folder.
Please refer to the docs to understand more!
We could use PrintWriter
class to write to a file, the constructor of this class could take a string file name, or a File
instance.
Notice that we could throw, or catch the exception this is thrown from the PrintWriter
constructor.
We could read a text file using Scanner
, we will use the Scanner
constructor that takes a File
instance as an argument.
Notice that Scanner
has a method called hasNext
, which indicates if there is any more information, this is not very useful when we are taking input from the keyboard, but very useful in files!
We will cover 12.13 Case Study: Web Crawler from the book
Programming
Java
IUG