---
# System prepended metadata

title: Computer Programming II Pre-Lab 5
tags: [Computer Engineering, IUG, Computer Programming II, Pre-Lab]

---

---
title: Computer Programming II Pre-Lab 5
---
<h1 style='border: none'><center>Computer Programming II Pre-Lab 5</center></h1>
<h2 style='border: none'><center>Exceptions</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/02</span></h6>
<h6>Parts of this Lab were adapted from work done by Mohammed Nafiz ALMadhoun and  Mohammed AlBanna</h6>
---

# Exception Handling in Java

Exception Handling is a mechanism to handle runtime errors such as `ClassNotFoundException`, `IOException`, `SQLException`, `RemoteException`, etc.

## Hierarchy of Java Exception classes

The Java class `Throwable` is the root of Java exception hierarchy similarly, class Exception is the root of all other exception classes.

<center>

![](https://i.imgur.com/DDGqoRs.png)
</center>

## Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

## Difference between Checked and Unchecked Exceptions

### Checked Exception

The classes which directly inherit `Throwable` class except `RuntimeException` and `Error` are known as checked exceptions e.g. `IOException`, `SQLException` etc. Checked exceptions are checked at compile-time.

### Unchecked Exception

The classes which inherit `RuntimeException` are known as unchecked exceptions e.g. `ArithmeticException`, `NullPointerException`, `ArrayIndexOutOfBoundsException` etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.


#### Error

Error is irrecoverable e.g. `OutOfMemoryError`, `VirtualMachineError`, `AssertionError` etc.

## Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.



| Keyword  | Description |
| -------- | ----------- |
| `try`      | The `try` keyword is used to specify a block where we should place exception code. The try block must be followed by either `catch` or `finally`. It means, we can't use try block alone.     |
| `catch`      | The `catch` block is used to handle the exception. It must be preceded by `try` block which means we can't use `catch` block alone. It can be followed by `finally` block later.     |
| `finally`      |   The `finally` block is used to execute the important code of the program. It is executed whether an exception is handled or not.   |
| `throw`      | The `throw` keyword is used to throw an exception.     |
| `throws`      | The `throws` keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.     |


## Common Scenarios of Java Exceptions

```java=
int a = 50 / 0; //ArithmeticException 

/* ******************************************** */

String s = "abc";
int i = Integer.parseInt(s); //NumberFormatException 

/* ******************************************** */

int arr[] = new int[5];
arr[10] = 5; //ArrayIndexOutOfBoundsException 
```

## Examples

### Example 1:

```java=
class JavaExceptionExample {
    public static void main(String args[]) {
        try {
            int num = 100 / 0;
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
        System.out.println("rest of the code...");
    }
}
```

output:

```
/ by zero
rest of the code...
```

### Example 2:

Here, we handle the exception using the parent class exception.

```java=
class JavaExceptionExample {
    public static void main(String[] args) {
        try {
            int num = 50 / 0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println("rest of the code");
    }
}
```
output:

```
/ by zero
rest of the code
```

### Example 3:

In this example, along with try block, we also enclose exception code in a catch block.

```java=
class JavaExceptionExample {
    public static void main(String[] args) {
        try {
            int num1 = 50 / 0;
        } catch (Exception e) {
            int num2 = 50 / 0;
        }
        System.out.println("rest of the code");
    }
}
```
output:

```java
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at JavaExceptionExample.main(Test.java:6)
```

### Example 4:

In this example, we handle the generated exception `Arithmetic Exception` with a different type of exception class `ArrayIndexOutOfBoundsException`.

```java=
class JavaExceptionExample {
    public static void main(String[] args) {

        try {
            int num = 50 / 0;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e);
        }
        System.out.println("rest of the code");
    }
}

```
output:
```java
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at JavaExceptionExample.main(Test.java:5)
```

## Java Multi-catch block

A `try` block can be followed by one or more `catch` blocks. Each `catch` block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.

#### Points to remember:

* At any time only one exception occurs and at any time only one catch block is executed. 
* All catch blocks must be ordered from most specific to most general, i.e. catch for `ArithmeticException` must come before catch for `Exception`.


### Example 5:

```java=
class JavaExceptionExample {
    public static void main(String[] args) {

        try {
            int[] a = new int[5];
            a[4] = 30 / 0;

        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurs");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occurs");
        } catch (Exception e) {
            System.out.println("Parent Exception occurs");
        }
        System.out.println("rest of the code");
    }
}
```
output:
```
Arithmetic Exception occurs
rest of the code
```

### Example 6:

In this example, try block contains two exceptions. But at a time only one  exception occurs and its corresponding catch block is invoked.

```java=
class JavaExceptionExample {
    public static void main(String[] args) {

        try {
            int[] a = new int[5];
            a[5] = 30 / 0;
            System.out.println(a[10]);

        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurs");

        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occurs");

        } catch (Exception e) {
            System.out.println("Parent Exception occurs");
        }
        System.out.println("rest of the code");
    }
}
```
output:
```
Arithmetic Exception occurs
rest of the code
```

### Example 7:

In this example, we generate `NullPointerException`, but didn't provide the corresponding exception type. In such case, the catch block containing the parent exception class Exception will invoked.

```java=
class JavaExceptionExample {
    public static void main(String[] args) {


        try {
            String s = null;
            System.out.println(s.length());

        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurs");

        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occurs");

        } catch (Exception e) {
            System.out.println("Parent Exception occurs");

        }
        System.out.println("rest of the code");
    }
}
```
output:
```
Parent Exception occurs
rest of the code
```

### Example 8:

Let's see an example, to handle the exception without maintaining the order of  exceptions (i.e. from most specific to most general).

```java=
class JavaExceptionExample {
    public static void main(String[] args) {
        
        try {
            int[] a = new int[5];
            a[5] = 30 / 0;

        } catch (Exception e) {
            System.out.println("common task completed");

        } catch (ArithmeticException e) {
            System.out.println("task1 is completed");

        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("task 2 completed");
        }

        System.out.println("rest of the code...");
    }
}
```


<span style="color:#e20000" >**Compilation Error**</span>, why?


## Java finally block

* Java `finally` block is a block that is used to execute important code such as closing connection, stream etc. 
* Java `finally` block is always executed whether exception is handled or not. 
* Java `finally` block follows try or catch block.


### Example 9:

In this example, we generate `NullPointerException`, but didn't provide the corresponding exception type. In such case, the catch block containing the parent exception class Exception will invoked.

```java=
class JavaExceptionExample {
    public static void main(String[] args) {
        try {
            int num = 25 / 5;
            System.out.println(num);
        } catch (NullPointerException e) {
            System.out.println(e);
        } finally {
            System.out.println("finally block is always executed");
        }
        System.out.println("rest of the code...");
    }
}
```
output:
```
5
finally block is always executed
rest of the code...
```


### Example 10:

Let's see the java finally example where exception occurs and not handled.

```java=
class JavaExceptionExample {
    public static void main(String[] args) {
        try {
            int num = 25 / 0;
            System.out.println(num);

        } catch (NullPointerException e) {
            System.out.println(e);
        } finally {
            System.out.println("finally block is always executed");
        }
        System.out.println("rest of the code...");
    }
}
```

output:
```java
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at JavaExceptionExample.main(Test.java:4)
```

## Java throw keyword

The Java `throw` keyword is used to explicitly throw an exception.



### Example 11:

In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome.

```java=
class JavaExceptionExample {
    public static void main(String args[]) {
        validate(13);
        System.out.println("rest of the code...");
    }
    public static void validate(int age) {
        if (age < 18) {
            throw new ArithmeticException("not valid");
        } else {
            System.out.println("welcome");
        }
    }
}
```

output:
```java
Exception in thread "main" java.lang.ArithmeticException: not valid
	at JavaExceptionExample.validate(Test.java:8)
	at JavaExceptionExample.main(Test.java:3)
```

### Example 12:


```java=
class JavaExceptionExample {
    public static void main(String[] args) {
        try {
            validate(13);
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
        System.out.println("rest of the code...");
    }
    public static void validate(int age) {
        if (age < 18) {
            throw new ArithmeticException("not valid");
        } else {
            System.out.println("welcome");
        }
    }
}
```

output:
```java
not valid
rest of the code...
```

## Java throws keyword

The Java `throws` keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.


### Example 13:


```java=
import java.io.IOException;
class JavaExceptionExample {
    public static void main(String[] args) {
        JavaExceptionExample obj = new JavaExceptionExample();
        obj.p();
        System.out.println("finally");
    }
    public void m() throws IOException {
        throw new IOException("error");
    }
    public void n() throws IOException {
        m();
    }
    public void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("exception handled in p()");
        }
    }
}
```

output:
```
exception handled in p()
finally
```

## Exception Handling with Method Overriding in Java

### If the superclass method does not declare an exception

#### Case 1: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.

```java=
import java.io.IOException;
class ParentException {
    void msg() {
        System.out.println("parent");
    }
}
class ChildException extends ParentException {
    void msg() throws IOException {
        System.out.println("TestExceptionChild");
    }
    public static void main(String args[]) {
        ParentException p = new ChildException();
        p.msg();
    }
}
```

<span style="color:#e20000" >**Compilation Error**</span>


#### Case 2: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.

```java=
class ParentException {
    void msg() {
        System.out.println("parent");
    }
}
class ChildException extends ParentException {
    void msg() throws ArithmeticException {
        System.out.println("TestExceptionChild");
    }
    public static void main(String args[]) {
        ParentException p = new ChildException();
        p.msg();
    }
}
```

output:
```
TestExceptionChild
```

### If the superclass method declares an exception

#### Subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

```java=
class ParentException {
    void msg() throws ArithmeticException{
        System.out.println("parent");
    }
}
class ChildException extends ParentException {
    void msg() throws Exception {
        System.out.println("TestExceptionChild");
    }
    public static void main(String args[]) {
        ParentException p = new ChildException();
        p.msg();
    }
}
```

<span style="color:#e20000" >**Compilation Error**</span>

#### In case subclass overridden method declares same exception.


```java=
class ParentException {
    void msg() throws Exception {
        System.out.println("parent");
    }
}
class ChildException extends ParentException {
    void msg() throws Exception {
        System.out.println("TestExceptionChild");
    }
    public static void main(String args[]) {
        ParentException p = new ChildException();
        try {
            p.msg();
        } catch (Exception e) {
        }
    }
}
```

output:
```
TestExceptionChild
```

#### In case subclass overridden method declares subclass exception

```java=
class ParentException {
    void msg() throws Exception {
        System.out.println("parent");
    }
}
class ChildException extends ParentException {
    void msg() throws ArithmeticException{
        System.out.println("TestExceptionChild");
    }
    public static void main(String args[]) {
        ParentException p = new ChildException();
        try {
            p.msg();
        } catch (Exception e) {
        }
    }
}
```

output:
```
TestExceptionChild
```

#### In case subclass overridden method declares no exception

```java=
class ParentException {
    void msg() throws Exception {
        System.out.println("parent");
    }
}
class ChildException extends ParentException {
    void msg(){
        System.out.println("TestExceptionChild");
    }
    public static void main(String args[]) {
        ParentException p = new ChildException();
        try {
            p.msg();
        } catch (Exception e) {
        }
    }
}
```

output:
```
TestExceptionChild
```

## Java Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.


```java=
class CustomException extends Exception {
    String msg;
    CustomException(String msg) {
        super(msg);
        this.msg = msg;
    }
    public static void main(String[] args) {
        try {
            testCustomException();
        } catch (CustomException ex) {
            System.out.println(ex.getMessage());
            System.out.println("Exception");
        }
    }
    public static void testCustomException() throws CustomException {
        throw new CustomException("Custom Exception");
    }
    @Override
    public String getMessage() {
        return this.msg;
    }
}
```

output:
```
Custom Exception
Exception
```


###### tags: `Computer Programming II` `Pre-Lab` `IUG` `Computer Engineering`

<center>End Of Pre-Lab 5</center>