Java/C3/Exception-Handling/English

From Script | Spoken-Tutorial
Jump to: navigation, search
Visual Cue
Narration
Slide 1

Exception Handling

Welcome to the spoken tutorial on Exception Handling.
Slide 2

Learning Objectives

  • What is an Exception
  • Checked and Unchecked Exceptions
  • Handling the Exceptions using
    • try-catch block
    • finally block
In this tutorial we will learn about:
  • What is an exception
  • Checked and unchecked exceptions
  • Handling the exceptions using
    • try-catch block and
    • finally block
Slide 3

Software Requirements

  • Ubuntu 16.04 OS
  • JDK 1 .8
  • Eclipse 4.3.1
Here we are using
  • Ubuntu Linux 16.04 OS
  • JDK 1 .8 and
  • Eclipse 4.3.1
Slide 4

Prerequisites

To follow this tutorial, you must have knowledge of basics of Java and Eclipse IDE.

If not, for relevant Java tutorials, please visit the link shown.

Slide 5(a)

Exceptions

  • An exception is an unexpected event, which occurs during the execution
  • It interrupts the normal flow and results in an abnormal termination.
  • Exceptions are classified as
  • unchecked exceptions and
  • checked exceptions.
An exception is an unexpected event, which occurs during the execution of a program.


It interrupts the normal flow of the program and results in an abnormal termination.


Based on their occurrence, exceptions are classified as

  • unchecked exceptions and
  • checked exceptions.
In Eclipse IDE, create a project called ExceptionDemo Now we will open eclipse and create a new project called ExceptionDemo.


Inside this project we will create the necessary classes to demonstrate exception handling.

Right click on src folder and right-click New-> Class and type the class name as Marks and hit Enter We will create a new class Marks.
//Copy and paste the code.

public static void main(String[] args) {

int[] marks={30,40,35,34,45};

int a=0;


System.out.println("Mark List");

for(int i=0;i<5;i++){

System.out.println(marks[i]);

}}

Now type the following code to represent the Marks class.


This program prints the marks of 5 students that is stored in an array marks.

Click on run icon


Highlight the output

Let us run this program and verify the output.

We can see that the values in the array are getting printed.

Let us check what will happen if we are trying to access an array element which is not existing.
Type the following code (before printing the array)

System.out.println("\t"+marks[50]);

Highlight the index 50

Now type the following code.

We know that there are only 5 elements in our array.

But in this statement we are trying to access the element at index 50 which is not existing.

Click on run icon


Highlight the error Message

ArrayIndexOutOfBoundsException and

at Marks.main(Marks.java:7)


Highlight the print statement

Let us run this program now.


We can see that the program terminates with an error message:

ArrayIndexOutOfBoundsException “at line number 7.


The error message indicates the details of the exception like

  • type of exception
  • where it occurred
  • and other details.


Note that the print statement is not executed as the program terminates after the error.


This is an example of Unchecked exception.

Slide 7

Unchecked Exception

  • Unchecked Exceptions are called as Runtime Exceptions
  • They handle the programming bugs and logical errors such as
    • Dividing a number by zero
    • Accessing an array element which is not existing
  • Unchecked exceptions are called as Runtime exception as it is checked only during the execution.
  • They handle the programming bugs and logical errors such as
    • Dividing a number by zero and
    • Accessing an array element which is not existing
Now let us learn about how to handle an exception using try catch block.
Slide 8

Handling Exceptions

Highlight the portion of the code which can raise the exception


Highlight Exception e

Highlight the portion of code inside catch block

This portion of the code within a try block, can possibly raise an exception.


The corresponding catch block can receive the exception details in object e.


Inside the catch block we can write the code for

  • displaying error messages or
  • recovering from the error
Switch to eclipse Now let us switch to eclipse.
Type the code to add try block

try{

System.out.println("\t"+marks[50]);

}

First let us add a try block around the code which caused the exception like this.
Copy the following code

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Array Overflow Exception occurred");

}


Highlight "Array Overflow Exception occurred"


Highlight the Exception object e

Now we have to add a corresponding catch block.


So type the following code.


Here we are printing a custom message “Array Overflow Exception occurred”


Inside the round brackets we have created an instance of ArrayIndexOutOfBoundsException.


So this block can catch exceptions of type ArrayIndexOutOfBoundsException.

Click on run icon


Highlight the output ie Printing the array

Now let us run the program.


We can see that the error message gets printed.


But this time, note that printing the marks array is also executed.


In this way we can handle exceptions.

Next let us see how to use multiple catch blocks.

We can use them when different types of exceptions are raised by a block.

Insert the following code inside the try block (before the line of code System.out.println("\t"+marks[50]);)


System.out.println(marks[2]/a);


Highlight the above line of code

Type the following code inside the try block.


This line of code divides an array element by zero as the value of a is zero.


So an ArithmeticException will be raised first.

Type the following code

catch(ArithmeticException e)

{

System.out.println("Arithmetic Exception occurred");

}

Let us now add one more catch block to handle the ArithmeticException.


So type the following code after the existing catch block.

Click on run icon


Highlight the error message in the output


Let us run the program again.


This time the error message "Arithmetic Exception occurred" gets printed as it is caught first.


The remaining portion of the code outside the try catch block executes.

Slide 9

Checked Exceptions

  • They are checked at compile time.
  • They must be handled before running the program

Example:

  • Accessing a File which is not existing
  • Accessing a Network System when the network is down


Next let us see about checked exceptions.


Checked exceptions are checked at compile time.


So they must be handled before running the program.


For example:

  • Accessing a file which is not existing or
  • Accessing a network system when the network is down
Switch to Eclipse, create a new class MarksFile Now let us switch to Eclipse and create a new class MarksFile.
Type main and press control+space Let us add main method.
Type the following code

FileReader fr=null;


Highlight FileReader fr=null;


Highlight FileReader

Now we want to read a file located in the computer.


So type the following code.


Here the FileReader object fr is initialized as null.


FileReader object can be used to access and read a particular file.

Point the error


Click on the error and import the class


Go to the top of the code file and highlight the import statement

Eclipse will show an error.


To rectify the error, click on it and double click import FileReader java dot io.


The FileReader class is imported from the java dot io package.


We will learn about package and its usage in detail in a later tutorial.

Type the following code

fr = new FileReader("/home/spoken/Marks");


Highlight "/home/spoken/Marks


Point the error

To allow fr to access a file called Marks which is located in the home folder, type the following code.


The path shown here is to be replaced with that of your system's home folder.


Now an error comes up. It indicates that this line of code can create a FileNotFoundException.

Click on the error and double click Surround with a try catch block.


Click on the error and double click Surround with try/catch.


We can see that Eclipse automatically inserts the try catch block to rectify this error.


So we can understand that this is a checked exception.

Go to the MarksFile class Next let us see how to use finally block.
Copy the following code

finally{

System.out.println("Inside finally block");

}

Type the following code.


finally block usually follows a try-catch block .


The code inside this block is executed whether exception has occurred or not.


It contains a print statement.

Type fr.close();


Now let us close the file reference inside the finally block.


So type, fr dot close

Point the error


Click on the error and double click Surround with try/catch

Now Eclipse indicates that this will raise an IOException.


So click on the error and double click Surround with try/catch.

Click on run icon Now let us run the program.
Highlight FileNotFound Exception


Highlight NullPointerException


Highlight the print statement

Inside finally block

We can see that FileNotFoundException message is printed.


This is because we don't have a file named Marks in our home folder.


We can also see a NullPointerException as fr still refers to a null value.


But we can see that the print statement inside finally block gets executed.

So click on Files in the Ubuntu desktop and go inside the home folder Let us now create a text file Marks in our home folder.
In the eclipse show the path

D:\\Marks.txt

If you are a windows user, create a text file in your local drive and mention its path.


For example it can be specified as D:\\Marks.txt

Click on run icon Let us now run the program again.
Highlight the output

Inside finally block

We can verify that there are no exceptions once the Marks file is created.


And “Inside finally block” gets printed.


The cleanup operation i.e closing the FileReader Object fr is also executed successfully.

With this we come to the end of this tutorial.


Let us summarize.

Slide 10

Summary

  • What is an Exception
  • Checked and Unchecked Exceptions
  • Handling the Exceptions using
    • try-catch block
    • finally block
In this tutorial we have learnt about
  • What is an exception
  • Checked and unchecked exceptions
  • Handling the exceptions using the
    • try-catch block and
    • finally block
Slide 10

Assignment

Learn about another Runtime Exception called NullPointerException


Refer to the Java program named Demo.java provided in the assignment section.


An exception will be raised when you run this code.


Identify the code which is responsible for the exception.


Rectify it using a try-catch block

As an assignment,


Learn about another Runtime Exception called NullPointerException.


Refer to the Java program named Demo.java provided in the Assignment link of this tutorial.


An exception will be raised when you run this code.


Identify the code which is responsible for the exception.


Rectify it using a try-catch block.

About Project

(retain the slide as in TEX file)

The video at the following link summarizes the Spoken Tutorial Project.


Please download and watch it.

About Workshops

(retain the slide as in TEX file)

The Spoken Tutorial Project Team

• Conducts workshops using spoken tutorials • Gives certificates on passing the online tests


For more details, please write to us.

About NMEICT

(retain the slide as in TEX file)

Spoken Tutorial Project is funded by the NMEICT, MHRD, Government of India.


More information on this Mission is available at the link shown.

Contributor slide

(retain the slide as in TEX file)

This script has been contributed by:

Dept. of Information

Technology, Amal Jyothi College of Engineering


This is Priya from IIT Bombay. Thanks for joining.

Contributors and Content Editors

Nancyvarkey, Priyacst