Java/C3/Custom-Exceptions/English

From Script | Spoken-Tutorial
Jump to: navigation, search

Title of script: Custom Exceptions

Author: Joms Antony

Keywords: Custom Exceptions, User defined exceptions, throw keyword, throws keyword, video tutorial, Java


Visual Cue
Narration
Slide 1


Welcome to the spoken tutorial on custom exceptions.
Slide 2

Learning Objectives

  • Custom exceptions
  • Usage of throw and throws keywords
In this tutorial we will learn about:
  • Custom exceptions and
  • Usage of throw and throws keywords
Slide 3

Software Requirements

  • Ubuntu Linux 16.04
  • JDK 1 .7
  • Eclipse 4.3.1
To record this tutorial, I am using
  • Ubuntu Linux 16.04 OS
  • JDK 1 .7 and
  • Eclipse 4.3.1
Slide 4

Prerequisites

To follow this tutorial, you must have basic knowledge of Exceptions Handling in Java.

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

Slide 5

Custom Exception

  • Custom exception is a user defined exception class.
  • It is usually created as checked exceptions.
  • It is used to customize the exception according to user need.


First let us learn about custom exceptions.


  • Custom exception is a user defined exception class.
  • It is usually created as checked exceptions.
  • It is used to customize the exception according to user need.
In Eclipse IDE, create a project called CustomExceptionDemo Now we will open eclipse and create a new project called CustomExceptionDemo.


Inside this project we will create the necessary classes to demonstrate custom exceptions.

Right click on src folder and click New-> Class and type the class name as InvalidMarkException and hit Enter We will create a new class InvalidMarkException.
public class InvalidMarkException

Type

extends Exception

To make this as a type of exception class, it should be a subclass of Java exception class.


To do so, type extends Exception.

Click on Source -> Generate constructors from Superclass Click on Source menu and then select Generate constructors from Superclass.
Click on Deselect All


Now click on Deselect All button in the right hand side.
Select Exception(String)

Click OK button.


Highlight the inserted code

Then select the constructor with a single string argument and click on OK button at the bottom.


This string argument can be used to customize the message shown when this exception occurs.


<<PAUSE>>

Right click on src folder and click New-> Class -> StudentMarks Let us add another class named StudentMarks.
Copy the following code

int marks;

public StudentMarks(int marks) {

this.marks = marks;

}

Highlight “int marks;”

Highlight “public StudentMarks(int marks) { this.marks = marks;}”

Then type the following code.


This class contains only one variable named marks.

This constructor initializes the value of marks.

Copy the following code

public void validate()

{

if (marks<0 || marks>100)


throw new InvalidMarkException(marks+" is not a valid entry");

else

System.out.println("Entry OK");

}


Highlight “if (marks<0 || marks>100)”

Highlight “throw new InvalidMarkException(marks+" not a valid entry");”


Highlight “throw” and “marks not a valid entry”


Highlight "Entry OK"

Let us now add a method to validate the marks.


The normal range of marks is from 0 to 100.


If marks less than 0 or greater than 100 is processed, InvalidMarkException will be thrown.


For this, we need to use the throw keyword explicitly to throw a custom exception.


If the mark is a valid one, the message “Entry OK” will be displayed.

Highlight

throw new InvalidMarkException(marks+" is not a valid entry");

We can see that there is an error InvalidMarkException.


Let us check and resolve it.

Click on the error and double click “Add throws declaration”


Highlight the “throws InvalidMarkException”


So click on the error and double click “Add throws declaration”.


We can see that the error disappears once the “throws InvalidMarkException” is added to the method signature.

Highlight

public void validate() throws InvalidMarkException

Here we can see that the throws keyword is used along with methods.
Highlight

InvalidMarkException

It indicates that the method will raise the specified exception.
throw new InvalidMarkException(marks+" not a valid entry"); We have to provide the exception handling code when such a method is called.


<<PAUSE>>

Next to System.out.println("Entry OK"); statement, type

FileReader fr=null;

Next, let us perform a file access operation which will raise a FileNotFoundException.


So type the following code to create an instance of a FileReader class.

Point the error


Click on the error and double click import 'FileReader' (java.io).


Eclipse will show some errors as we have not imported the corresponding Java packages.


To rectify the same, click on the error and then double click import 'FileReader' (java.io).


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

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


Highlight "/home/spoken/Marks


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.

Point the error


d

Click on the error and double click Add throws declaration


An error shows that this line of code can raise a FileNotFoundException.


We can resolve it by adding this exception in the throws clause.

Highlight FileNotFoundException


Highlight throws InvalidMarkException, FileNotFoundException

We can see that FileNotFoundException is also added to the throws clause.


We can handle multiple exceptions using throws as shown here.


<<PAUSE>>

Copy the following code

public static void main(String[] args) {

StudentMarks m1=new StudentMarks(40);


m1.validate();


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

}

We will now create the main method inside the StudentMarks class and verify the results.



Highlight StudentMarks m1=new StudentMarks(40);


Highlight m1.validate();

Here we create an object m1 initialized with 40 as the value for marks.

In the next line we invoke the method validate using the object m1.

Point the error We can see that there is an error when the validate method is invoked.


It says that this method will raise the

InvalidMarkException and FileNotFoundException

Point to throws in the drop down options


Double click Surround with try/catch


To resolve the error, we can add throws clause to main method as we did earlier


But it is recommended to use try and catch block.


So, double click Surround with try/catch.


Now the necessary try-catch blocks are added and the exception has been handled.

Click run icon Now let us run this program.
Point to Entry OK, rest of the code It displays “Entry OK” and “rest of the code”.


This happens because the value of marks 40 is a valid entry.

Modify “Marks m1=new Marks(-10);” Let us now change the value to -10 which is an invalid entry.
Click run icon We will run the program again.
Highlight the output

InvalidMarkException: -10 is not a valid entry


Highlight the message “rest of the code”

Now we can see that the InvalidMarkException is thrown as -10 is an invalid entry.


Since we have handled the exception, we can see the message “rest of the code”


Instead if we use “throws” clause, this message “rest of the code” will not be printed.


Also the program will be terminated.


So it is better to use a try catch block when a method is called inside the main method.


With this we come to the end of this tutorial.


<<PAUSE>>

Slide 8

Summary


  • What is a Custom Exception
  • Usage of throw and throws keywords
  • How to create and use custom exceptions
Let us summarize.


In this tutorial we have learned about

  • What is a Custom Exception
  • Usage of throw and throws keywords
  • How to create and use custom exceptions
Slide 9

Assignment


  • Create a custom exception class InvalidAgeException
  • Create another class Age and create a constructor to initialize the value of age
  • Create validate() method to throw the above exception if age < 18


As an assignment


Create a custom exception class called InvalidAgeException


Create another class Age and create a constructor to initialize the value of age


Also create a method validate to throw an exception if the age is less than 18

Slide 9A

Assignment


  • Create objects inside the main method and invoke the validate() method
  • Provide exception handling using try-catch blocks
  • Verify the custom exception class
Create objects inside the main method and invoke the validate() method


Provide exception handling using try-catch blocks wherever required.


Verify the custom exception class.

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 and

• 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:

Department of Information Technology, Amal Jyothi College of Engineering


This is Priya from IIT Bombay, signing off. Thanks for joining.

Contributors and Content Editors

Nancyvarkey, Priyacst