[go: up one dir, main page]

0% found this document useful (0 votes)
37 views17 pages

Unit 3 Oops

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

➔What is an Exception in Java?

An exception is an unwanted or unexpected event that occurs during the execution of the
program, that disrupts the flow of the program.
For example, if a user is trying to divide an integer by 0 then it is an exception, as it is not
possible mathematically.
There are various types of interruptions while executing any program like errors, exceptions, and
bugs. These interruptions can be due to programming mistakes or due to system issues.
Depending on the conditions they can be classified as errors and exceptions.
1. Exception
• As mentioned earlier exceptions are unwanted conditions that disrupt the flow of the
program.
• Exceptions usually occur due to the code and can be recovered.
• Exceptions can be of both checked(exceptions that are checked by the compiler) and
unchecked(exceptions that cannot be checked by the compiler) type.
• They can occur at both run time and compile time.
In Java, exceptions belong to java.lang.Exception class.

2. Error

• An error is also an unwanted condition but it is caused due to lack of resources


and indicates a serious problem.
• Errors are irrecoverable, they cannot be handled by the programmers.
• Errors are of unchecked type only.
• They can occur only at run time.
• In java, errors belong to java.lang.error class.
• Eg: OutOfMemmoryError.

➔What is Exception Handling in java?


• Exception handling in java is a mechanism to handle unwanted interruptions like
exceptions and continue with the normal flow of the program.
• Java uses try-catch blocks and other keywords like finally, throw, and throws to handle
exceptions. JVM(Java Virtual Machine) by default handles exceptions, when an exception
is raised it will halt the execution of the program and throw the occurred exception.
class SampleCode
{
public static void main(String args[])
{
Sysytem.out.println("Hello World!");
int a = 10;
int b = 0;
System.out.println(a / b);
System.out.println("Welcome to java programming.");
System.out.println("Bye.")
}
}
Hello World!
Exception in thread "main" java.lang.ArithmeticException: / by zero
at SampleException.main
In the above code, the first three lines in the main method are executed properly. At the 4th line,
an integer is divided by 0, which is not possible and an exception is raised by JVM(Java Virtual
Machine). In this case, the exception is not handled by the programmer which will halt the program
in between by throwing the exception, and the rest of the lines of code won't be executed.

➔How does JVM handles an Exception?

Java exceptions raised during the program execution are nothing but objects of the respective
exception class in the hierarchy shown above. The exceptions have a naming and inheritance
hierarchy to the main exception class in java i.e. Throwable class. All java exception objects
support the toString() method, which returns the full name of the exception class as an output to
the command prompt, which helps to understand the exceptional condition.

Whenever an exception has occurred inside a method, the method creates an exception object and
hands it over to JVM.

This object contains the name and description of the exception and the current state of the program
where the exception has occurred. This is called the process of object creation and handing it over
to JVM is known as throwing an Exception. This object is an exception that is further handled by
JVM.
When an exception is raised there is an ordered list of the methods that had been called by JVM to
get the method where the exception has occurred this list is called Call Stack.

JVM searches through this call stack to get the proper code to handle the occurred exception, this
code block is known as an Exception handler. When an appropriate handler is found JVM handles
the exception according to the code in the handler and shows the state of the program.

But if it is not able to find the handler JVM uses the default exception handler, which is part of the
run-time system. But this default exception handler throws an exception and terminates the
program abnormally.

➔Hierarchy of Java Exception Classes


As java is an object-oriented language every class extends the Object class. All exceptions and
errors are subclasses of class Throwable. Throwable is the base/superclass of exception handling
hierarchy in java. This class is further extended in different classes like exception, error, and so on.
Types of Exceptions Handling in Java
1. Checked Exceptions
• Checked exceptions are those exceptions that are checked at compile time by the
compiler.
• The program will not compile if they are not handled.
• These exceptions are child classes of the Exception class.
• IOException, ClassNotFoundException, InvocationTargetException, and SQL Exception
are a few of the checked exceptions in Java.

2. Unchecked Exceptions
• Unchecked exceptions are those exceptions that are checked at run time by JVM, as the
compiler cannot check unchecked exceptions,
• The programs with unchecked exceptions get compiled successfully but they give
runtime errors if not handled.
• These are child classes of Runtime Exception Class.
• ArithmeticException, NullPointerException, NumberFormatException,
IndexOutOfBoundException are a few of the unchecked exceptions in Java.

➔How does a Programmer Handles an Exception?


Customized exception handling in java is achieved using five keywords: try, catch, throw,
throws, and finally. Here is how these keywords work in short.
1. try block
• try block is used to execute doubtful statements which can throw exceptions.
• try block can have multiple statements.
• Try block cannot be executed on itself, there has to be at least one catch block or finally
block with a try block.
• When any exception occurs in a try block, the appropriate exception object will be
redirected to the catch block, this catch block will handle the exception according to
statements in it and continue the further execution.
• The control of execution goes from the try block to the catch block once an exception
occurs.
2. catch block
• catch block is used to give a solution or alternative for an exception.
• catch block is used to handle the exception by declaring the type of exception within the
parameter.
• The declared exception must be the parent class exception or the generated exception
type in the exception class hierarchy or a user-defined exception.
• You can use multiple catch blocks with a single try block.
3. finally block
• finally block is associated with a try, catch block.
• It is executed every time irrespective of exception is thrown or not.
• finally block is used to execute important statements such as closing statement, release
the resources, and release memory also.
• finally block can be used with try block with or without catch block.
Example:-

public class Main {

public static void main(String[] args) {

try {

int data = 100/0;

System.out.println(data);

} catch (Exception e) {

System.out.println("Can't divide integer by 0!");

} finally {

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

➔Custom Exceptions in Java

Custom exceptions are user-defined exceptions.


We can create exceptions as per the requirement by extending the Exception class that belongs to
java.lang package.
These are the exceptions related to business logic where a developer wants the user to give input
in the required format and if user fails to do so an exception is raised and user gets instructions of
what the problem is and how it can be resolved. It is useful for the application users or the
developer to understand the exact problem.
1. throw keyword

• throw keyword in java is used to throw an exception explicitly.


• We can throw checked as well as unchecked exceptions (compile-time and runtime) using
it.
• We specify the class of exception object which is to be thrown. The exception has some
error message with it that provides the error description.
• We can also define our own set of conditions for which we can throw an exception
explicitly using the throw keyword.
• The flow of execution of the program stops immediately after the throw statement is
executed and the nearest try block is checked to see if it has a catch statement that
matches the type of exception.
• It tries to find all the catch blocks until it finds the respective handler, else it transfers the
control to the default handler which will halt the program.

2. throws keyword

• throws keyword in java is used in the signature of the method to indicate that this method
might throw one of the exceptions from java exception class hierarchy.
• throws keyword is used only for checked exceptions like IOException as using it with
unchecked exceptions is meaningless(Unchecked exceptions can be avoided by
correcting the programming mistakes.)
• throws keyword can be used to declare an exception.

Example: In case a user wants to set Age limit we can use custom exceptions and give the
required comment as an output.

class InvalidProductException extends Exception


{
public InvalidProductException(String s)
{
super(s);
}
}
public class CustomExample1
{
void Check(int weight) throws InvalidProductException
{
if (weight < 50)
{
throw new InvalidProductException("Product Invalid");
}
}

public static void main(String args[])


{
CustomExample1 obj = new CustomExample1();
try {
obj.productCheck(35);
} catch (InvalidProductException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
}
}
➔Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains
all the classes required for input and output operations.

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

1. System.out.println("simple message");
2. System.err.println("error message");
3. int i=System.in.read(); //returns ASCII code of 1st character
4. System.out.println((char)i); //will print the character
➔Byte Stream and Character Stream
There are two types of streams in Java- Byte Stream and Character Stream.
Byte streams in Java are used to perform input and output operations of 8-bit bytes while the
Character stream is used to perform input and output operations for 16-bits Unicode.
Character streams are useful in reading or writing text files which are processed character by
character.
Byte Streams are useful to read/write data from raw binary files.
➔Byte Stream
Byte Stream are Further divided into two parts:

1. OutputStream
• Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
• Class Hierarchy for OutputStream:
OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.

BufferedOutputStream :
This is used for Buffered Output Stream.
DataOutputStream :
This contains method for writing java standard data types.
FileOutputStream :
This is used to write to a file.
PrintStream :
This contains the most used print() and println() method
2. InputStream
• Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
• Class Hierarchy for InputStream:
InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.

BufferedInputStream
It is used for Buffered Input Stream.
DataInputStream
It contains method for reading java standard datatypes.
FileInputStream
This is used to reads from a file.
Example: Copy the content of one file to another
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes


{
public static void main(String[] args)
{
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("infile.txt");
out = new FileOutputStream("outfile.txt");
int c;

while ((c = in.read()) != -1)


{
out.write(c);
}
}catch(IOException e) {
System.out.println("IO Exception");
}
}
}
➔Character Stream
Character Stream are Further divided into two parts:
1. Reader Hierarchy

Reader : Abstract class for reading character streams.


BufferedReader : It extends Reader. Reads text from a character-input stream, buffering
characters so as to provide for the efficient reading of characters, arrays, and lines.
InputStreamReader : It extends Reader. An InputStreamReader is a bridge from byte streams to
character streams: It reads bytes and decodes them into characters using a specified charset. The
charset that it uses may be specified by name or may be given explicitly, or the platform’s default
charset may be accepted.
FileReader : It extends InputStreamReader. Convenience class for reading character files. 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.
StringReader : It extends Reader. A character stream whose source is a string.

2. Writer Hierarchy

Writer: Abstract class for writing to character streams.


BufferedWriter: It extends Writer. Writes text to a character-output stream, buffering characters
so as to provide for the efficient writing of single characters, arrays, and strings.
OutputStreamWriter: It extends Writer. An OutputStreamWriter is a bridge from character
streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
The charset that it uses may be specified by name or may be given explicitly, or the platform’s
default charset may be accepted.
PrintWriter: It extends Writer. Prints formatted representations of objects to a text-output stream.
StringWriter: It extends Writer. A character stream that collects its output in a string buffer, which
can then be used to construct a string.
FileWriter: It extends OutputStreamWriter. Convenience class for writing character files. The
constructors of this class assume that the default character encoding and the default byte-buffer
size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a
FileOutputStream.
import java.io.*;
public class CopyFile
{

public static void main(String args[])


{
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}catch(IOException e){
System.out.println(“Input Output Exception”);
}finally {
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
➔InputStreamReader and OutputStreamWritter
The InputStreamReader class works with other input streams. It is also known as a bridge between
byte streams and character streams. This is because the InputStreamReader reads bytes from the
input stream as characters.

import java.io.InputStreamReader;
import java.io.FileInputStream;

class Main {
public static void main(String[] args) {

char[] array = new char[100];

try {

FileInputStream file = new FileInputStream("input.txt");

InputStreamReader input = new InputStreamReader(file);

input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);

input.close();
}

catch(Exception e) {
e.getStackTrace();
}
}
}
The OutputStreamWriter class works with other output streams. It is also known as a bridge
between byte streams and character streams. This is because the OutputStreamWriter converts its
characters into bytes.

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class Main {

public static void main(String args[]) {

String data = "This is a line of text inside the file.";

try {

FileOutputStream file = new FileOutputStream("output.txt");

OutputStreamWriter output = new OutputStreamWriter(file);

output.write(data);

output.close();
}

catch (Exception e) {
e.getStackTrace();
}
}
}

You might also like