0% found this document useful (0 votes)
26 views

Unit 6

Uploaded by

Sudani Nishchay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Unit 6

Uploaded by

Sudani Nishchay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Exception Handling

What are Java Exceptions?

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.

Major reasons why an exception Occurs


 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Out of bound
 Null reference
 Type mismatch
 Opening an unavailable file
 Database errors
 Arithmetic errors

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.

Difference between Error and Exception


Let us discuss the most important part which is the differences between Error and
Exception that is as follows:
 Error: An Error indicates a serious problem that a reasonable application should not try to
catch.
 Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy
All exception and error types are subclasses of the class Throwable, which is the base class of
the hierarchy. One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch. NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do
with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
s to define their own exceptions.

Exceptions can be categorized in two ways:


1. Built-in Exceptions

 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.

 Checked Exceptions: Checked exceptions are called compile-time exceptions because


these exceptions are checked at compile-time by the compiler.

 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

Java try and catch

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.

The try and catch keywords come in pairs:


Syntax

try {

// Block of code to try

catch(Exception e) {

// Block of code to handle errors

Consider the following example:


This will generate an error, because myNumbers[10] does not exist.

public class Main {


public static void main(String[ ] args) {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]); // error!

The output will be something like this:


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
Example

public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

The output will be:


Something went wrong.

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:
Example

public class Main {


public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

} finally {

System.out.println("The 'try catch' is finished.");

The output will be:


Something went wrong.
The 'try catch' is finished.

The throw keyword

The throw statement allows you to create a custom error.

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

public class Main {

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Access denied - You must be at least 18 years old.");

}
else {

System.out.println("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(15); // Set age to 15 (which is below 18...)

The output will be:


Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least
18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)

If age was 20, you would not get an exception:


Example

checkAge(20);

The output will be:


Access granted - You are old enough!

User-defined Custom Exception in Java


An exception is an issue (run time error) that occurred during the execution of a program. When
an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets executed.
Java provides us the facility to create our own exceptions which are basically derived classes of
Exception. Creating our own Exception is known as a custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the exception according to
user needs. In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’ keyword.
For example, MyException in the below code extends the Exception class.

Why use custom exceptions?


Java exceptions cover almost all the general types of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
Following are a few of the reasons to use custom exceptions:
 To catch and provide specific treatment to a subset of existing Java exceptions.
 Business logic exceptions: These are the exceptions related to business logic and workflow.
It is useful for the application users or the developers to understand the exact problem.
In order to create a custom exception, we need to extend the Exception class that belongs
to java.lang package.
Example: We pass the string to the constructor of the superclass- Exception which is obtained
using the “getMessage()” function on the object created.

Java

// A Class that represents use-defined exception


class MyException extends Exception {
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
// A Class that uses above MyException
public class Main {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new MyException("GeeksGeeks");
}
catch (MyException ex) {
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage());
}
}
}

Output
Caught
GeeksGeeks
Files

File handling is an important part of any application.

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

import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

The File class has many useful methods for creating and getting information about files. For
example:

Method Type Description

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file

length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory


mkdir() Boolean Creates a directory

Create and Write To Files


Create a File

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

import java.io.File; // Import the File class

import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile {

public static void main(String[] args) {

try {

File myObj = new File("filename.txt");

if (myObj.createNewFile()) {

System.out.println("File created: " + myObj.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) {

System.out.println("An error occurred.");

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

File myObj = new File("C:\\Users\\MyName\\filename.txt");


Write To a File

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

import java.io.FileWriter; // Import the FileWriter class

import java.io.IOException; // Import the IOException class to handle errors

public class WriteToFile {

public static void main(String[] args) {

try {

FileWriter myWriter = new FileWriter("filename.txt");

myWriter.write("Files in Java might be tricky, but it is fun enough!");

myWriter.close();

System.out.println("Successfully wrote to the file.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

The output will be:


Successfully wrote to the file.

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:

import java.io.File; // Import the File class


import java.io.FileNotFoundException; // Import this class to handle errors

import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {

public static void main(String[] args) {

try {

File myObj = new File("filename.txt");

Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

String data = myReader.nextLine();

System.out.println(data);

myReader.close();

} catch (FileNotFoundException e) {

System.out.println("An error occurred.");

e.printStackTrace();

The output will be:


Files in Java might be tricky, but it is fun enough!

import java.io.File; // Import the File class

public class GetFileInfo {


public static void main(String[] args) {

File myObj = new File("filename.txt");

if (myObj.exists()) {

System.out.println("File name: " + myObj.getName());

System.out.println("Absolute path: " + myObj.getAbsolutePath());


System.out.println("Writeable: " + myObj.canWrite());

System.out.println("Readable " + myObj.canRead());

System.out.println("File size in bytes " + myObj.length());

} else {

System.out.println("The file does not exist.");

The output will be:


File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0

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

 public void close() throws IOException closes the reader.


 public long skip(long n) throws IOException –Skips characters. This method will block
until some characters are available, an I/O error occurs, or the end of the stream is reached.
Parameters:
n – The number of characters to skip
The following program depicts how to read from the ‘text’ file using FileReader

// Reading data from a file using FileReader


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;

// check if File exists or not


FileReader fr=null;
try
{
fr = new FileReader("text");
}
catch (FileNotFoundException fe)
{
System.out.println("File not found");
}

// read from FileReader till the end of file


while ((ch=fr.read())!=-1)
System.out.print((char)ch);

// close the file


fr.close();
}
}

Delete a File

To delete a file in Java, use the delete() method:


Example
import java.io.File; // Import the File class

public class DeleteFile {


public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}

The output will be:


Deleted the file: filename.txt

Delete a Folder

You can also delete a folder. However, it must be empty:


Example
import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}

The output will be:


Deleted the folder: Test
Cloneable Interface in Java

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

// Java program to Demonstrate the


// application of Cloneable interface
import java.io.*;
import java.util.*;
class Student {
// attributes of Student class
String name = null;
int id = 0;
// default constructor
Student() {}
// parameterized constructor
Student(String name, int id)
{
this.name = name;
this.id = id;
}
public static void main(String[] args)
{
// create an instance of Student
Student s1 = new Student("Ashish", 121);
// Try to clone s1 and assign
// the new object to s2
Student s2 = s1.clone();
}
}

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;

// By implementing Cloneable interface


// we make sure that instances of class A
// can be cloned.
class A implements Cloneable {
int i;
String s;

// A class constructor
public A(int i, String s)
{
this.i = i;
this.s = s;
}

// Overriding clone() method


// by simply calling Object class
// clone() method.
@Override
protected Object clone()
throws CloneNotSupportedException
{
return super.clone();
}
}

public class Test {


public static void main(String[] args)
throws CloneNotSupportedException
{
A a = new A(20, "GeeksForGeeks");

// cloning 'a' and holding


// new cloned object reference in b

// down-casting as clone() return type is Object


A b = (A)a.clone();

System.out.println(b.i);
System.out.println(b.s);
}
}

Output
20
GeeksForGeeks

Deep Copy using clone() method


Deep Object Cloning is like creating an exact copy of the original object by copying the fields
from the original object to the cloned object. A separate memory is allocated for the cloned objects
where the original object content is copied. clone() method can create both shallow and deep
copy of the original object based on the implementation of it. Deep copy creates a new memory
with the contents same as the original object. That’s why when we change the content of the
original object after cloning, the changes do not reflect in the clone object. There are types of
copies such as Deep, Shallow, and Lazy Copy. The below code explains the deep copy using the
clone() method.
 Java

// A Java program to demonstrate deep copy


// using clone()
import java.util.ArrayList;

// An object reference of this class is


// contained by Test2
class Test {
int x, y;
}
// Contains a reference of Test and implements
// clone with deep copy.
class Test2 implements Cloneable {
int a, b;

Test c = new Test();

public Object clone() throws CloneNotSupportedException


{
// Assign the shallow copy to new reference variable
Test2 t = (Test2)super.clone();
t.c = new Test();
// Create a new object for the field c
// and assign it to shallow copy obtained,
// to make it a deep copy
return t;
}
}

public class Main {


public static void main(String args[])
throws CloneNotSupportedException
{
Test2 t1 = new Test2();
t1.a = 10;
t1.b = 20;
t1.c.x = 30;
t1.c.y = 40;

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;

// Change in object type field of t2 will not


// be reflected in t1(deep copy)
System.out.println(t1.a + " " + t1.b + " " + t1.c.x
+ " " + t1.c.y);
System.out.println(t3.a + " " + t3.b + " " + t3.c.x
+ " " + t3.c.y);
}
}

Output
10 20 30 40
100 20 300 40

Comparable Interface in Java with Examples

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.

Using Comparable Interface

 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.*;

class Pair implements Comparable<Pair> {


String x;
int y;

public Pair(String x, int y)


{
this.x = x;
this.y = y;
}

public String toString()


{
return "(" + x + "," + y + ")";
}

@Override public int compareTo(Pair a)


{
// if the string are not equal
if (this.x.compareTo(a.x) != 0) {
return this.x.compareTo(a.x);
}
else {
// we compare int values
// if the strings are equal
return this.y - a.y;
}
}
}

public class GFG {


public static void main(String[] args)
{

int n = 4;
Pair arr[] = new Pair[n];

arr[0] = new Pair("abc", 3);


arr[1] = new Pair("a", 4);
arr[2] = new Pair("bc", 5);
arr[3] = new Pair("a", 2);

// Sorting the array


Arrays.sort(arr);

// printing the
// Pair array
print(arr);
}

public static void print(Pair[] arr)


{
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}

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"} }

Input: { {"abc", "last"}, {"pklz", "yelp"}, {"rpng", "note"}, {"ppza", "xyz"} }


Output: { {"abc", "last"}, {"pklz", "yelp"}, {"ppza", "xyz"}, {"rpng", "note"} }

 Java

import java.io.*;
import java.util.*;

class Pair implements Comparable<Pair> {


String firstName;
String lastName;

public Pair(String x, String y)


{
this.firstName = x;
this.lastName = y;
}

public String toString()


{
return "( " + firstName + " , " + lastName + " )";
}

@Override public int compareTo(Pair a)


{
// if the string are not equal
if (this.firstName.compareTo(a.firstName) != 0) {
return this.firstName.compareTo(a.firstName);
}
else {
// we compare lastName if firstNames are equal
return this.lastName.compareTo(a.lastName);
}
}
}

public class GFG {


public static void main(String[] args)
{

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");

// Sorting the array


Arrays.sort(arr);

// printing the
// Pair array
print(arr);
}

public static void print(Pair[] arr)


{
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}

Output:
Before Sorting:
( raj , kashup )
( rahul , singh )
( reshmi , dubey )
( rahul , jetli )

After Sorting:
( rahul , jetli )
( rahul , singh )
( raj , kashup )
( reshmi , dubey )

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy