Try   HackMD

Programming II Lab 5

Exception Handling and Text I/O

The Islamic University of Gaza
Engineering Faculty
Department of Computer Engineering
Author: Mohammed Nafiz ALMadhoun2021/03/13

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.

Exception Handling

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:

import java.util.Scanner public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter two numbers: "); int n1 = input.nextInt(); int n2 = input.nextInt(); try { System.out.printf("%d/%d=%d", n1, n2, n1/n2); } catch (ArithmeticException ex) { System.out.println("Couldn't prefomre division"); } } }

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.

import java.util.*; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter two numbers: "); try { int n1 = input.nextInt(); int n2 = input.nextInt(); System.out.printf("%d/%d=%d", n1, n2, n1/n2); } catch (InputMismatchException ex) { System.out.println("Please enter an integers!"); } catch (ArithmeticException ex) { System.out.println("Couldn't prefomre division"); } } }

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.

Defining an Exception

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.

public class Blog { public static Post getPost (int index) throws PostNotFoundException { if (index >= posts.size()) throw new PostNotFoundException(index); return posts.get(index); } } class PostNotFoundException extends Exception { public PostNotFoundException (int requestedIndex) { super ("Post " + requestedIndex + " Not Found!"); } }

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.

Finally Block

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.

try { statments... } catch (Exception ex) { statments... } finally { statments... }

Important Note: don't use exceptions for expected errors, check them with an if will make your code much better!

Text I/O

As we have already covered simple text operations, this section should be an easy section for you!

File class

The file is a class that implements different methods to manipulate files and folder.

Please refer to the docs to understand more!

public class Test { public static void main(String[] args) { File f = new File("testFolder/"); f.mkdir(); } }

Writing Text File

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.

import java.io.*; public class Test { public static void main(String[] args) { try { PrintWriter pw = new PrintWriter("test.txt"); pw.println("This is a test"); pw.close(); } catch (Exception ex) { System.out.println("Couldn't write to the file!"); } } }

Notice that we could throw, or catch the exception this is thrown from the PrintWriter constructor.

Reading Text File

We could read a text file using Scanner, we will use the Scanner constructor that takes a File instance as an argument.

import java.util.*; import java.io.*; public class Test { public static void main(String[] args) { try { File f = new File("test.txt"); Scanner input = new Scanner(f); String firstLine = input.nextLine(); System.out.println(firstLine); input.close(); } catch (Exception ex) { System.out.println("Couldn't read the file!"); } } }

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

tags: Programming Java IUG
End Of Lab 5