Beruflich Dokumente
Kultur Dokumente
Java Exception:
Exception:
Exception handling:
An exception is an event that terminates the program normally and remaining code
will executed.
Main objective:
The main objective of the handling the exception is to get the normal termination of the
program and rest of code will executed.
Ans: Five
1. Un-checked Exception:
An unchecked exception is an exception while execution the program the
compiler unable to check the exception is called as unchecked exception.
This exception occurred at runtime.
If the program is contains unchecked exception, but code is compiled and at
runtime JVM display the exception.
1. ArithmeticExcepption.
2. NumberNotFoundException.
3. NullPointerException.
4. ArrayIndexOutOfBoundsException.etc..
Examples 1:ArithmeticException
class JavaException
{
public static void main(String args[])
{
System.out.println("Hi JAVA-1 ");
System.out.println("Hi JAVA-2 ");
System.out.println(10/0);
System.out.println("Hi JAVA-3 ");
System.out.println("Hi JAVA-4 ");
}
}
2
Page
In above example contains there are five statements and while executing the above
code the compiler unable to check the exception , code will compiled successfully
and at runtime JVM display the exception.
At the statement line no 3 will have an exception
System.out.println(10/0); //ArithmeticExcepption.
At statement-1 and statement -2 will executed and rest of code will not
executed. see below lines:
If we are dividing any number by zero that produces the exception at runtime that is
ArithmeticException.
Example 2:ArrayIndexOutOfBoundsException
at MyClass.main(MyClass.java:6)
Page
Example 3: NullPointerException
class NullPoiter
{
public static void main (String[] args)
{
String str1 = null;
String str2 = “JAVA”;
if (str1.equals(str2))
{
System.out.print("Same");
}
else
{
System.out.print("Not Same");
}
}
}
After execution:
at NullPoiter.main(NullPoiter.java:13)
Example 4: NumberFormatException:
class NumberFormatException
{
public static void main (String[] args)
{
// Initializing String variable with null value
String str = null;
int i=Integer.parseInt(str);
System.out.println(i);
}
}
4
Page
After Executing:
2. Checked Exception:
The checked exceptions are the exceptions which are checked by the compiler
it is called as checked exception, code will not compiled.
If the program is containing the checked exception code is not executed.
Example is :IOException, SQLException etc. Checked exceptions are checked
at compile-time.
1.try-catch block
2.throws
Example1: FileNotFoundException:
import java.io.*;
class IOExceptions
{
public static void main(String[] args)
{
FileReader file = new FileReader("C:\\Desktop\\a.txt");
}
}
After executing:
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling.
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
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 important code of the program. It
is executed whether an exception is handled or not.
int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
try block
Inside try block we write the block of statements which causes executions at run time in
other words try block always contains problematic statements.
The "try" keyword is used to specify a block where we should place exception code. The
try block must be followed by either catch or finally. It means, we can't use try block
alone.
If any exception occurs in try block then CPU controls comes out to the try block and
executes appropriate catch block.
After executing appropriate catch block, even though we use run time statement, CPU
control never goes to try block to execute the rest of the statements.
Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.
Syntax
try
{
.....
}
catch()
{
....
}
Each and every try block must contains at least one catch block. But it is highly
recommended to write multiple catch blocks for generating multiple user friendly error
messages.
One try block can contains another try block that is nested or inner try block can be
8
possible.
Page
try
{
.......
try
{
.......
}
}
catch block
Inside catch block we write the block of statements which will generates user friendly
error messages.
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.
classExceptionDemo
{
publicstaticvoid main(String[] args)
{
int a=10, b=0;
b=a/0;
System.out.println("Denominator not be zero");
}
}
Abnormally terminate program and give a message like below, this error message is not
understandable by user so we convert this error message into user friendly error message,
9
Output
You can write multiple catch blocks for generating multiple user friendly error messages
to make your application strong. You can see below example.
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.
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
10
o All catch blocks must be ordered from most specific to most general, i.e. catch for
Page
Syntax is:
try
{
//Exception code
}
catch(exception_name ref-var)
{
//Handling errors
}
catch(exception_name ref-var)
{
//Handling errors
}
---------------------------------------------------------
Example: 1
classExceptionDemo
{
public static void main(String[] args)
{
int a=10, b=0, div;
try
{
div=a/b;
System.out.println("Result: "+div);
}
catch(ArithmeticExceptionae)
{
System.out.println("Denominator not be zero");
}
catch(Exception e)
{
System.out.println("Enter valid number");
}
}
}
Output
Example 2:
class MultipleCatchBlock2
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
System.out.println(a[10]);
}
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");
}
}
OUTPUT:
ArrayIndexOutOfBounds Exception occurs
Example 3:
public class MultipleCatchBlock3
{
public static void main(String[] args)
{
try
{
String s=null;
System.out.println(s.length());
}
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");
}
}
OUTPUT:
Parent Exception occurs
Example 4:
class MultipleCatchBlock4
{
public static void main(String args[])
{
try
{
int x=10/0;
}
catch(Exception e)
{
System.out.println("common task completed");
}
OUTPUT:
Common task completed
Rest of the code…..
Note:
catch(Exception e)
{
System.out.println("common task completed");
}
Here Exception is a root class for all exceptions. If any exception occur in try automatically
executed this above catch block.
1. ArithmeticException
2. ArrayIndexOutOfBoundException
3. FileNotFoundException
14
Page
Note: - throw keyword is used to handover user created exception object to JVM whether it is
predefined exception class or user defined exception class but it is always recommended
throw custom exception.
Step 1:- create the Exception object explicitly by the developer by using new keyword.
newInvalidAgeException("Shridhar not eligible");
Step 2:- handover (throw) user created Exception object to jvm by using throw keyword.
throw new InvalidAgeException ("Shridhar not eligible");
Example:-
importjava.util.*;
class Test
{
static void status(int age)
{
if (age<18)
{
throw new InvalidAgeException("not eligible for vote");
}
else
{
System.out.println("welcome to the voting");
}
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age=s.nextInt();
Test.status(age);
System.out.println("rest of the code");
}
}
15
Page
OUTPUT:
Run 1: Run 2:
C:\Users\staff1\Desktop>javac Test.java C:\Users\staff1\Desktop>java Test
C:\Users\staff1\Desktop>java Test please enter your age
please enter your age 12
26 Exception in thread "main"
welcome to the voting java.lang.ArithmeticException: not eligible for vote
rest of the code at Test.validate(Test.java:8)
at Test.main(Test.java:19)
InvaliedAgeException.java:-
//default constructor
}
16
Page
importjava.util.Scanner;
classInvalidAgeException extends Exception
{
//Default Constructor.
}
OUTPUT:
Run 1: Run 2:
C:\Users\staff1\Documents>javac Test.java C:\Users\staff1\Documents>java Test
C:\Users\staff1\Documents>java Test Enter ur age
Enter ur age 15
23 Exception in thread "main" InvalidAgeException
Marry at Test.status(Test.java:19)
at Test.main(Test.java:28)
17
Page
importjava.util.Scanner;
classInvalidAgeException extends Exception
{
public InvalidAgeException(String s)
{
super(s); // Call constructor of parent Exception
}
}
Marry at Main.status(Main.java:24)
at Main.main(Main.java:33)
Page
Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java.
Stream:-
Stream is nothing but sequence of data, and it is called as stream means stream of water
continuous flow.
In general, a stream means continuous flow of data. Streams are clean way to deal with
input/output without having every part of your code understand the physical.
Stream is a communication channel between source and destination &A stream is a sequence of
data.
Input stream:-Program uses Input stream to read the data from a source one item at a time.
19
Page
DataOutputStream An output stream that contain method for writing java standard
data type
These classes define several key methods. Two most important are
Java encapsulates Stream under java.io package. Java defines two types of streams.
They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
While working with streams we will get two exceptions mainly FileNotFoundException
21
,IOException& these two exceptions are checked exceptions so must handle these exception
by using try-catch blocks or throws keyword.
Page
Character streams:-
Program uses character stream to perform input & output of character data. All
character stream classes developed based on Reader & Writer classes.
To demonstrate how the character stream works file I/O provided two main classes
FileReader
oIt is used to read the data from source one item at a time.
oTo read the data from source use read() method of FileInputStream class.
publicint read() throws java.io.IOException;
read() method returns first character Unicode value in the form of integer
value.
FileWriter
oIt is used to write the data to destination one item at a time.
oTo write the data to destination use write() method of FileOutputStream class.
public void write(intunicode) throws java.io.IOException;
write() method is taking Unicode value of the character as a parameter.
Example: CharacterStream
-----------------------------------------
Save As: CharacterStream
import java.io.*;
classCharacterStream
{
public static void main(String[] args) throws FileNotFoundException,IOException
{
FileReaderfr = new FileReader("abc.txt");
FileWriterfw = new FileWriter("xyz.txt");
int c;
while((c=fr.read())!=-1)
{
fw.write(c);
}
fr.close();
fw.close();
22
}
}
Page
Note :
1. In CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int
variable holds a byte value in its last 8 bits. CopyCharacters is very similar to CopyBytes.
2. The most important difference is that CopyCharacters uses FileReader and FileWriter for input
and output in place of FileInputStream and FileOutputStream.
3. Notice that both CopyBytes and CopyCharacters use an int variable to read to and write from.
However, in CopyCharacters, the int variable holds a character value in its last 16 bits; in
CopyBytes, the int variable holds a byte value in its last 8 bits.
BufferedReader
oIt is used to read the data from source file in line by line format.
oTo read the data use readLine() method of BufferedReader class .
publicjava.lang.StringreadLine() throws java.io.IOException;
The readLine() method returns first line of the text file in the form of String.
PrintWriter
oIt is used to write the data to destination file in line by line format.
oTo write the data to file use println() method of PrintWriter class.
public void println(java.lang.String);
The above method used to write the data to destination file.
Buffered Streams:-
In previous examples we are using un-buffered I/O .This means each read and write request
is handled directly by the underlying OS.
In normal streams each request directly triggers disk access it is relatively expensive &
performance is degraded.
--------------------------------------------------
import java.io.*;
public class Main123
{
public static void main(String[] args) throws FileNotFoundException,IOException
{
BufferedReaderbr = new BufferedReader(new FileReader("abc.txt"));
BufferedWriterbw = new BufferedWriter(new FileWriter("xyz.txt"));
PrintWriter
oIt is used to write the data to destination file in line by line format.
oTo write the data to file use println() method of PrintWriter class.
public void println(java.lang.String);
The above method used to write the data to destination file.
25
Multithreading in java
Page
Thread:
o A thread is a light-weight smallest part of a process that can run concurrently with the
other parts (other threads) of the same process.
o Threads are independent because they all have separate path of execution that’s the
reason if an exception occurs in one thread, it doesn’t affect the execution of other
threads.
o All threads of a process share the common memory.
Multithreading:
Example:
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a
single thread.
26
Page
Multitasking
o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the processes is high.
Multithreading Multitasking
Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class extends
Object class and implements Runnable interface.
Main Thread:
When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of our program, because it is the one that is executed when our
program begins.
Properties:
It is the thread from which other “child” threads will be started.
Often, it must be the last thread to finish execution because it performs various
shutdown actions
The main thread is created automatically when our program is started. To control it we must
obtain a reference to it. This can be done by calling the method currentThread( ) which is
present in Thread class. This method returns a reference to the thread on which it is called.
The default priority of Main thread is 5 and for all remaining user threads priority will be
inherited from parent to child.
Creating Threads:
We can make our class runnable as thread by extending the class java.lang.Thread.
This gives us access to all the methods directly. It includes the following steps:
The run() method has been inherited by Thread class. We have to override this method in
order to implement the code to be executed by our thread.
Syntax:
run( )
{
…………… //Thread code here.
……………
}
When we start the new thread , Java calls the start method’s run() method, so it is the run()
where the all action takes place.
30
Page
The above first line creates the object for the MyThread class. The thread will run
this object is not yet running. The thread is in a newborn state.
The second line calls the start() method to move into the runnable state. Then
the java runtime will schedule (Thread Schedule) the thread to run by invoking
its run() method. Now, the thread is said to be in the running state.
OUTPUT
----------------
thread is running...
31
Page
The runnable interface has an undefined method run( ) with void as return type, and it takes
in no arguments. The method summary of the run( ) method is given below-
Method Description
public void run( ) This method takes in no arguments. When the object of a class
implementing Runnable class is used to create a thread, then the run
method is invoked in the thread which executes separately.
The Runnable interface provides a standard set of rules for the instances of classes
which wish to execute code when they are active. The most common use case of the
Runnable interface is when we want only to override the run method. When a thread is
started by the object of any class which is implementing Runnable, then it invokes the run
method in the separately executing thread.
The Runnable interface declares the run( ) method that is required for implementation
thread in our programs. To do this, we must perform the steps listed below:
Implementing Runnable
It is the easiest way to create a thread by implementing Runnable. One can create a thread on
any object by implementing Runnable. To implement a Runnable, one has only to implement
the run method.
In this method, we have the code which we want to execute on a concurrent thread. In this
Page
method, we can use variables, instantiate classes, and perform an action like the same way the
main thread does. The thread remains until the return of this method. The run method
establishes an entry point to a new thread.
The thread will execute the code which is mentioned in the run() method of the
Runnable object passed in its argument.
}
Page
Output:
Raju’s task
Ravi’s task
Anil’s task
Output
JavaThread’s task is running…..
JavaThread’s task is running…..
JavaThread’s task is running…..
35
Page
Thread Priorities:-
1. Every Thread in java has some property. It may be default priority provided be the JVM or
customized priority provided by the programmer.
2. The valid range of thread priorities is 1 – 10. Where 1 is lowest priority and 10 is highest
priority.
3. The default priority of main thread is 5. The priority of child thread is inherited from the
parent.
4. Thread defines the following constants to represent some standard priorities.
5. Thread Scheduler will use priorities while allocating processor the thread which is having
highest priority will get chance first and the thread which is having low priority.
6. If two threads having the same priority then we can’t expect exact execution order it
depends upon Thread Scheduler.
7. The thread which is having low priority has to wait until completion of high priority
threads.
8. Three constant values for the thread priority.
a) MIN_PRIORITY = 1
b) NORM_PRIORITY = 5
c) MAX_PRIORITY = 10
Thread class defines the following methods to get and set priority of a Thread.
Public final int getPriority()
Public final void setPriority(int priority)
Here ‘priority’ indicates a number which is in the allowed range of 1 – 10. Otherwise we
will get Runtime exception saying “IllegalArgumentException”.
Java program to print the name of current thread and priority and set the
priority by user.
Output:
C:\Users\staff1\Desktop>java ThreadDemo
current Thread name = Thread-0
current Thread name = Thread-1
current Thread priority = 10
current Thread priority = 1
37
Page
import java.io.*;
class Thread1 extends Thread
{
public void run()
{
System.out.println("Thread is running...");
}
}
class Thread2 implements Runnable
{
public void run()
{
System.out.println("Runnable is running...");
}
}
class Lab13
{
public static void main(String args[])
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t3.start();
t4.start();
}
}
Output:
-------------------------------------
Thread is running…
Runnable is running…
38
Page
14. Write a Java program that creates three threads. First thread displays
“Good Morning” every one second, the second thread displays “Hello”
every two seconds and the third thread displays “Welcome” every three
seconds.
import java.lang.*;
class ThreadOne extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Good morning");
}
}
System.out.println("Hello");
}
}
39
Page
t1.start();
t2.start();
t3.start();
}
}
Output:
Good Morning.
Hello.
Welcome.
40
Page
The isAlive() method returns true if the thread upon which it is called is still running
otherwise it returns false.
But, join() method is used more commonly than isAlive(). This method waits until the thread
on which it is called terminates.
Using join() method, we tell our thread to wait until the specified thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time
for which you want to wait for the specified thread to terminate.
}
Page
catch(InterruptedException ie)
{
// do something
}
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
----------------------------------------------------------------------------------
OUTPUT:
E:\RajuVathari\THIRD SEMESTER\LAB PROGRAMS>java MyThread
t1 thread is alive :true
t2 thread is alive :true
Child thread is running...
Child thread is running...
I am child thread...!!!
I am child thread...!!!
42
Page
Output:
--------------------------------
r1
r1
r2
r2
43
Page