Unit 6
Unit 6
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of
a program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains information
about the exception, such as the name and description of the exception and the state of the
program when the exception occurred.
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle errors.
Checked Exception
Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple words,
if a program throws an unchecked exception, and even if we didn’t handle or declare it, the
program would not give a compilation error.
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the
try block.
try {
catch(Exception e) {
System.out.println(myNumbers[10]); // error!
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
Example
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
} finally {
The throw statement is used together with an exception type. There are many exception types
available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, Securit
yException, etc:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
}
else {
checkAge(20);
Java
Output
Caught
GeeksGeeks
Files
Java has several methods for creating, reading, updating, and deleting files.
Java File Handling
The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:
Example
The File class has many useful methods for creating and getting information about files. For
example:
To create a file in Java, you can use the createNewFile() method. This method returns a boolean
value: true if the file was successfully created, and false if the file already exists. Note that the
method is enclosed in a try...catch block. This is necessary because it throws an IOException if
an error occurs (if the file cannot be created for some reason):
try {
if (myObj.createNewFile()) {
} else {
} catch (IOException e) {
e.printStackTrace();
}
File created: filename.txt
To create a file in a specific directory (requires permission), specify the path of the file and use
double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just
write the path, like: /Users/name/filename.txt
Example
In the following example, we use the FileWriter class together with its write() method to write
some text to the file we created in the example above. Note that when you are done writing to the
file, you should close it with the close() method:
Example
try {
myWriter.close();
} catch (IOException e) {
e.printStackTrace();
Read Files
In the following example, we use the Scanner class to read the contents of the text file we created
in the previous chapter:
try {
while (myReader.hasNextLine()) {
System.out.println(data);
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
if (myObj.exists()) {
} else {
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
This class inherited from the InputStreamReader Class.
The constructors of this class assume that the default character encoding and the default
byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
FileReader is meant for reading streams of characters. For reading streams of raw bytes,
consider using a FileInputStream.
Constructors:
FileReader(File file) – Creates a FileReader , given the File to read from
FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to
read from
FileReader(String fileName) – Creates a new FileReader , given the name of the file to
read from
Methods:
public int read () throws IOException – Reads a single character. This method will block
until a character is available, an I/O error occurs, or the end of the stream is reached.
public int read(char[] cbuff) throws IOException – Reads characters into an array. This
method will block until some input is available, an I/O error occurs, or the end of the
stream is reached.
public abstract int read(char[] buff, int off, int len) throws IOException –Reads
characters into a portion of an array. This method will block until some input is available,
an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read
Delete a File
Delete a Folder
The Java.lang.Cloneable interface is a marker interface. It was introduced in JDK 1.0. There is a
method clone() in the Object class. Cloneable interface is implemented by a class to
make Object.clone() method valid thereby making field-for-field copy. This interface allows the
implementing class to have its objects to be cloned instead of using a new operator.
Declaration
public interface Cloneable
Example 1: Below program explains that If you will try to Clone an object which doesn’t
implement the Cloneable interface, it will CloneNotSupportedException, which you may want
to handle.
Java
Output:
prog.java:28: error: incompatible types: Object cannot be converted to Student
Student s2 = s1.clone();
^
1 error
Example 2: Below code explains the proper usage of the Cloneable interface to make the
Object.clone() method legal. Classes that implement this interface should override the
Object.clone() method (which is protected) so that it can be invoked.
Java
// Java program to illustrate Cloneable interface
import java.lang.Cloneable;
// A class constructor
public A(int i, String s)
{
this.i = i;
this.s = s;
}
System.out.println(b.i);
System.out.println(b.s);
}
}
Output
20
GeeksForGeeks
Test2 t3 = (Test2)t1.clone();
t3.a = 100;
// Change in primitive type of t2 will not
// be reflected in t1 field
t3.c.x = 300;
Output
10 20 30 40
100 20 300 40
The Comparable interface is used to compare an object of the same class with an instance of that
class, it provides ordering of data for objects of the user-defined class. The class has to
implement the java.lang.Comparable interface to compare its instance, it provides the
compareTo method that takes a parameter of the object of that class. In this article, we will see
how we can sort an array of pairs of different data types on the different parameters of
comparison.
In this method, we are going to implement the Comparable interface from java.lang Package
in the Pair class.
The Comparable interface contains the method compareTo to decide the order of the
elements.
Override the compareTo method in the Pair class.
Create an array of Pairs and populate the array.
Use the Arrays.sort() function to sort the array.
Example 1
Given an array of Pairs consisting of two fields of type string and integer. you have to sort the
array in ascending Lexicographical order and if two strings are the same sort it based on their
integer value.
Sample I/O:
Input: { {"abc", 3}, {"a", 4}, {"bc", 5}, {"a", 2} }
Output: { {"a", 2}, {"a", 4}, {"abc", 3}, {"bc", 5} }
Input: { {"efg", 1}, {"gfg", 1}, {"cba", 1}, {"zaa", 1} }
Output: { {"cba", 1}, {"efg", 1}, {"gfg", 1}, {"zaa", 1} }
Java
import java.io.*;
import java.util.*;
int n = 4;
Pair arr[] = new Pair[n];
// printing the
// Pair array
print(arr);
}
Output:
Before Sorting:
(abc, 3);
(a, 4);
(bc, 5);
(a, 2);
After Sorting:
(a,2)
(a,4)
(abc,3)
(bc,5)
Note: if two strings are the same then the comparison is done based on the value.
Example 2
Given an array of Pairs consisting of two strings with first and last names. you have to sort the
array in ascending Lexicographical order of the first name and if two strings are the same sort it
based on their last name.
Sample I/O:
Input: { {"raj", "kashup"}, {"rahul", "singh"}, {"reshmi", "dubey"}, {"rahul", "jetli"} }
Output: { {"rahul", "jetli"}, {"rahul", "singh"}, {"raj", "kashup"}, {"reshmi", "dubey"} }
Java
import java.io.*;
import java.util.*;
int n = 4;
Pair arr[] = new Pair[n];
arr[0] = new Pair("raj", "kashup");
arr[1] = new Pair("rahul", "singh");
arr[2] = new Pair("reshmi", "dubey");
arr[3] = new Pair("rahul", "jetli");
// printing the
// Pair array
print(arr);
}
Output:
Before Sorting:
( raj , kashup )
( rahul , singh )
( reshmi , dubey )
( rahul , jetli )
After Sorting:
( rahul , jetli )
( rahul , singh )
( raj , kashup )
( reshmi , dubey )