(Lab-4 Manual) CS-204-DSA
(Lab-4 Manual) CS-204-DSA
Fall 2019
Lab-4 Manual
File I/O + Comparator + Exception Handling
v1.0
3/23/2019
Lab-4 Manual 2019
Exceptions in Java
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are
suitable to explain certain error situations. Below is the list of important built-in exceptions in
Java.
Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number
by 0");
}
}
}
NOTE: Copy the ArithmeticException_Demo.java code from the Code folder then compile
and run the code.
Page 1
Lab-4 Manual 2019
ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
public class IndexOutOfBoundException_Demo {
public static void main(String args[])
{
try {
int [] array = new int[10];
int c = array[15]; // accesing 15th element.
System.out.println ("Result = " + c);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println ("Index not Found !");
}
}
}
NOTE: Copy the IndexOutOfBoundException_Demo.java code from the Code folder then
compile and run the code.
StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size of
the string
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try {
String a = "This is like chipping ";
// length is 22
char c = a.charAt(24);
// accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("Index not found in
String");
}
}
}
NOTE: Copy the StringIndexOutOfBound _Demo.java code from the Code folder then
compile and run the code.
Page 2
Lab-4 Manual 2019
ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NullPointerException
This exception is raised when referring to the members of a null object. Null represents nothing
NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
RuntimeException
This represents any exception which occurs during runtime.
The user should create an exception class as a subclass of Exception class. Since all the
exceptions are subclasses of Exception class, the user should also make his class a subclass
of it. This is done as:
class MyException extends Exception
We can write a default constructor in his own exception class.
MyException(){}
We can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call super class(Exception) constructor
from this and send the string there.
MyException(String str)
{
super(str);
}
To raise exception of user-defined type, we need to create an object to his exception class
and throw it using throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
Page 3
Lab-4 Manual 2019
The following program illustrates how to create own exception class MyException.
Details of account numbers, customer names, and balance amounts are taken in the form of
three arrays.
In main() method, the details are displayed using a for-loop. At this time, check is done if
in any account the balance amount is less than the minimum balance amount to be kept in
the account.
If it is so, then MyException is raised and a message is displayed “Balance amount is
less”.
Page 4
Lab-4 Manual 2019
// default constructor
MyException() { }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");
Page 5
Lab-4 Manual 2019
NOTE: Copy the MyException.java code from the Code folder then compile and run the
code.
Page 6
Lab-4 Manual 2019
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
FileReader fileReader;
fileReader = new FileReader("src/testproject/input.txt");
Scanner input = new Scanner(fileReader);
while(input.hasNext()){
System.out.println(input.nextInt());
}//while
}//main
}//ScannerInput
NOTE: Copy the ScannerInput.java code from the Code folder. Crate an input.txt in your
package folder and add some data in that file and then compile and run the code.
Page 7
Lab-4 Manual 2019
1 boolean hasNext() Returns true if this scanner has another token in its input.
2 boolean Returns true if the next token in this scanner's input can be
hasNextDouble() interpreted as a double value using the nextDouble()
method.
3 boolean Returns true if the next token in this scanner's input can be
hasNextFloat() interpreted as a float value using the nextFloat() method.
4 boolean Returns true if the next token in this scanner's input can be
hasNextInt() interpreted as an int value in the default radix using the
nextInt() method.
5 String next() Finds and returns the next complete token from this
scanner..
6 String nextLine() Moves scanner position to the next line & returns the
value as a string.
Page 8
Lab-4 Manual 2019
In the previous example you have seen how you can take input from file now we will write some
content in file.
import java.io.FileWriter;
import java.io.IOException;
FileWriter fileWriter ;
fileWriter = new
FileWriter("src/testproject/output.txt");
fileWriter.write("Hello ");
fileWriter.write("To ");
fileWriter.write("DSA \n");
fileWriter.write("With ");
fileWriter.write("Course Code : CS- ");
fileWriter.write(String.valueOf(201));
fileWriter.close();
}//main
}//ScannerOutput
NOTE: Copy the FileOutput.java code from the Code folder. Crate an output.txt in your
package folder and then compile and run the code.
Page 9
Lab-4 Manual 2019
Syntax:
Page 10
Lab-4 Manual 2019
Page 11