---
# System prepended metadata

title: Computer Programming II Lab 5 v1.0
tags: [Computer Engineering, IUG, Lab, Computer Programming II]

---

---
title: Computer Programming II Lab 5 v1.0
---
<h1 style='border: none'><center>Computer Programming II Lab 5</center></h1>
<h2 style='border: none'><center>Exception Handling and Text I/O</center></h2>
<h5><center>The Islamic University of Gaza<br>Engineering Faculty<br>Department of Computer Engineering</center></h5>
<h6>Authors: Usama R. Al Zayan<span style="float:right">2023/03/05</span></h6>
<h6>Parts of this Lab were adapted from work done by Mohammed Nafiz ALMadhoun</h6>
---

## Lab 4: Time and Plan

| Tasks    | Timing   | 
| -------- | -------- |
| Quiz 1   | 10 min   |
| Task 1   | 60 min   |



<p style='text-align:justify'>
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.
</p>

## 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:
```java=
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.

```java=
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.

```java=
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.

```java=
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](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) to understand more!

```java=
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.

```java=
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.

```java=
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: `Computer Programming II` `Lab` `IUG` `Computer Engineering`
<center>End Of Lab 5</center>