0% found this document useful (0 votes)
10 views19 pages

Unit 2 Java-1-19

The document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on Exception Handling, Input/Output Basics, and Multithreading. It explains the types of exceptions, the exception hierarchy, and the use of keywords like try, catch, throw, and finally for managing exceptions. Additionally, it discusses Java's I/O streams, including OutputStream and InputStream, and their methods for handling file operations.

Uploaded by

dpsami11149
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)
10 views19 pages

Unit 2 Java-1-19

The document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on Exception Handling, Input/Output Basics, and Multithreading. It explains the types of exceptions, the exception hierarchy, and the use of keywords like try, catch, throw, and finally for managing exceptions. Additionally, it discusses Java's I/O streams, including OutputStream and InputStream, and their methods for handling file operations.

Uploaded by

dpsami11149
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/ 19

Unit -2nd OOP with JAVA

Exception Handling: The Idea behind Exception, Exceptions & Errors, Types of
Exception, Control Flow in Exceptions, JVM Reaction to Exceptions, Use of try, catch,
finally, throw, throws in Exception Handling, In-built and User Defined Exceptions,
Checked and Un-Checked Exceptions.

Input /Output Basics: Byte Streams and Character Streams, Reading and Writing File
in Java.

Multithreading: Thread, Thread Life Cycle, Creating Threads, Thread Priorities,


Synchronizing Threads, Inter-thread Communication.

2.1 Exceptions in Java

Exception Handling in Java is one of the effective means to handle runtime errors so
that the regular flow of the application can be preserved. Java Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.

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
 Opening an unavailable file

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.

Java Exception Hierarchy

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.
Exceptions can be categorized in two ways:
 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 Exception Keywords

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by either
catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.

Methods to print the Exception information:

//program to print the exception information using toString() method


import java.io.*;

class GFG1
{
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e)
{
System.out.println(e.toString());
}
}
}

Types of Exception in Java with Examples

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:

Built-in exceptions are the exceptions that 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.
1. ArithmeticException: It is thrown when an exceptional condition has occurred in
an arithmetic operation.
2. ArrayIndexOutOfBoundsException: 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.
3. ClassNotFoundException: This Exception is raised when we try to access a class
whose definition is not found
4. FileNotFoundException: This Exception is raised when a file is not accessible or
does not open.
5. IOException: It is thrown when an input-output operation failed or interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain the field (or
variable) specified
8. NullPointerException: This exception is raised when referring to the members of
a null object. Null represents nothing.

// Java program to demonstrate ArithmeticException


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");
}
}
}
// Java program to demonstrate StringIndexOutOfBoundsException

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("StringIndexOutOfBoundsException");
}
}
}

Java Try Catch Block

In Java exception is an “unwanted or unexpected event”, that occurs during the


execution of the program. When an exception occurs, the execution of the program
gets terminated. To avoid these termination conditions we can use try catch
block in Java. we will learn about Try, catch, throw, and throws in Java.

Why Does an Exception occur?


An exception can occur due to several reasons like a Network connection problem,
Bad input provided by a user, Opening a non-existing file in your program, etc Blocks
and Keywords Used For Exception Handling
1. try in Java

The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}

2. catch in Java

The catch block is used to handle the uncertain condition of a try block. A try block is
always followed by a catch block, which handles the exception that occurs in the
associated try block.

catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler. So, if you have to perform different tasks at the occurrence
of different exceptions, use java multi-catch block.

o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block

Example 1

Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

3.Java throw

The throw keyword in Java is used to explicitly throw an exception from a method or
any block of code. We can throw either checked or unchecked exception. The throw
keyword is mainly used to throw custom exceptions.
Syntax in Java throw
throw Instance
Example:
throw new ArithmeticException("/ by zero");

/ Java program that demonstrates the use of throw


class ThrowExcep {
static void fun() {
try {
throw new NullPointerException("demo"); }
catch (NullPointerException e) {
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception }
}

public static void main(String args[])


{
try {
fun();
}
catch (NullPointerException e) {
System.out.println("Caught in main.");
} } }

Important Points to Remember about throws Keyword


 throws keyword is required only for checked exceptions and usage of the throws
keyword for unchecked exceptions is meaningless.
 throws keyword is required only to convince the compiler and usage of the throws
keyword does not prevent abnormal termination of the program.
 With the help of the throws keyword, we can provide information to the caller of the
method about the exception.
finally in Java

A finally keyword is used to create a block of code that follows a try block. A finally block
of code is always executed whether an exception has occurred or not. Using a finally
block, it lets you run any cleanup type statements that you want to execute, no matter
what happens in the protected code.

Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block

we’ll explore all the possible combinations of try-catch-finally which may happen
whenever an exception is raised and how the control flow occurs in each of the given
cases.

o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.

1. Control flow in try-catch clause OR try-catch-finally clause

 Case 1: Exception occurs in try block and handled in catch block


 Case 2: Exception occurs in try-block is not handled in catch block
 Case 3: Exception doesn’t occur in try-block
2. try-finally clause

 Case 1: Exception occurs in try block


 Case 2: Exception doesn’t occur in try-block

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

OutPut:
Something went wrong.
The 'try catch' is finished.
2.2 Input /Output Basics

Java brings various Streams with its I/O package that helps the user to perform all the
input-output operations. These streams support all the types of objects, data-types,
characters, files etc to fully execute the I/O operations.

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.

We can perform file handling in Java by Java I/O API.

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

Let's see the code to print output and an error message to the console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.


1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character
Do You Know?
o How to write a common data to multiple files using a single stream only?
o How can we access multiple files by a single stream?
o How can we improve the performance of Input and Output operation?
o How many ways can we read data from the keyboard?
o What does the console class?
o How to compress and uncompress the data of a file?

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.

Let's understand the working of Java OutputStream and InputStream by the figure given
below.
OutputStream class

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.

Useful methods of OutputStream


Method Description

1) public void write(int)throws is used to write a byte to the current output stream.
IOException

2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

Output Stream Hierarchy

Input Stream class

InputStream class is an abstract class. It is the superclass of all classes representing an


input stream of bytes.

Useful methods of InputStream


Method Description

1) public abstract int read()throws reads the next byte of data from the input stream. It returns
IOException -1 at the end of the file.

2) public int available()throws returns an estimate of the number of bytes that can be read
IOException from the current input stream.

3) public void close()throws is used to close the current input stream.


IOException

Input Stream Hierarchy

Java FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file.

If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.

FileOutputStream class declaration

Let's see the declaration for Java.io.FileOutputStream class:

1. public class FileOutputStream extends OutputStream


FileOutputStream class methods
Method Description

protected void finalize() It is used to clean up the connection with the file output stream.

void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.

void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at
int len) offset off to the file output stream.

void write(int b) It is used to write the specified byte to the file output stream.

FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.

FileDescriptor getFD() It is used to return the file descriptor associated with the stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte


import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Output:

Success...

The content of a text file testout.txt is set with the data A.

testout.txt
A
Java FileOutputStream example 2: write string
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to java.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Output:

Success...

The content of a text file testout.txt is set with the data Welcome to javaTpoint.

testout.txt

Welcome to javaTpoint.

Java FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data. But, for reading streams of characters, it is recommended to
use FileReader class.

Java FileInputStream class declaration

Let's see the declaration for java.io.FileInputStream class:

1. public class FileInputStream extends InputStream


Java FileInputStream class methods
Method Description

int available() It is used to return the estimated number of bytes that can be read from
the input stream.

int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.

int read(byte[] b, int off, It is used to read up to len bytes of data from the input stream.
int len)

long skip(long x) It is used to skip over and discards x bytes of data from the input
stream.

FileChannel It is used to return the unique FileChannel object associated with the
getChannel() file input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

protected void finalize() It is used to ensure that the close method is call when there is no more
reference to the file input stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character


import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Note: Before running the code, a text file named as "testout.txt" is required to be
created. In this file, we are having following content:
Welcome to java.

After executing the above program, you will get a single character from the file which is
87 (in byte form). To see the text, you need to convert it into character.

Output:

W
Java FileInputStream example 2: read all characters

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Output:

Welcome to java

You might also like