JAVA Unit-V (3)
JAVA Unit-V (3)
Types of Errors
Que:
1. List and explain different types of errors.
2. Explain types of errors with example.
3. List types of Errors in exceptional handling and explain any one of them.
4. List types of error in Java.
Ans:
There are basically three types of errors that may arise during computer programs
execution:
1. Syntax errors
2. Runtime errors
3. Logic errors
1. Syntax errors
Syntax Errors, also known as Compilation errors are the most common type of errors.
Most Syntax errors are caused by mistakes that you make when writing code.
Common examples are:
Misspelled variable and function names
Missing semicolons
Improperly matches parentheses, square brackets, and curly braces
Incorrect format in selection and loop statements
2. Runtime errors
Run-time errors are those that appear only after you compile and run your code. It will
occur when your program attempts an operation that is impossible to carry out.
You can fix most run-time errors by rewriting the faulty code, and then recompiling and
running it.
Common examples are:
Trying to divide by a variable that contains a value of zero
Trying to open a file that doesn't exist
There is no way for the compiler to know about these kinds of errors when the program is
compiled.
3. Logic errors
Your code may compile and run without any Syntax Errors or Run-time Errors, but the
output of an operation may produce unwanted or unexpected results in response to user
actions. These types of errors are called Logic Errors.
Common examples are:
Multiplying when you should be dividing
Adding when you should be subtracting
Opening and using data from the wrong file
Displaying the wrong message
Page 1 of 23
Exception
Que:
1. Compare checked and Unchecked Exception.
Ans:
An exception (or exceptional event) is a problem that arises during the execution of a
program.
When an Exception occurs the normal flow of the program is disrupted and the program
terminates abnormally. Therefore, these exceptions are to be handled.
Following are some scenarios where an exception occurs.
A user has entered an invalid data.
A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
1. Checked exceptions –
For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
2. Unchecked exceptions
For example, if you have declared an array of size 5 in your program, and
trying to call the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexception occurs.
Page 2 of 23
3. Errors
Error is a problem that arises, which is not under the control of the user or
the programmer.
For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
Page 3 of 23
Exception Handling in Java
Que:
1. Explain Exception Handling.
2. Explain basic concept of Exception Handling.
Ans:
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
Program statements that you want to monitor for exceptions are contained within a try
block.
If an exception occurs within the try block, it is thrown. Your code can catch this
exception (using catch) and handle it.
System-generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be specified as such by a throws
clause.
Any code that absolutely must be executed after a try block completes is put in a finally
block.
This is the general form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
finally
{
// block of code to be executed after try block ends
}
Try…Catch
Que:
1. Explain Try and Catch with suitable example.
2. Explain ‘try’ and ‘catch’ statements in exceptional handling of Java language.
3. Write a program and explain try…catch block.
4. Explain ArrayIndexOutOfBound Exception in Java with example.
Ans:
Page 4 of 23
Code that you want to monitor, put inside in Try block.
Immediately following the try block, include a catch block that specifies the exception
type that we wish to catch.
Following program includes try block and catch block which processes the
ArithmeticException generated by the division-by-zero.
Example,
class AE
{
public static void main(String args[])
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) // catch divide-by-zero error
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Once an exception is thrown,program control transfers out of the try block into catch
block.
Throw
System-generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, the throw keyword is used.
it is used to explicitly throw exception in java.
The general form of throw is shown here:
throw ThrowableInstance;
class throwDemo
{
static void validate(int age)
{
try
{
if(age<16)
{
throw new ArithmeticException("Invalid Age");
}
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}
validate(age);
}
}
Page 7 of 23
Throws
The throws keyword is used to declare that a method may throw one or some
exceptions.
It can propagate exception to the calling method.
Calling method must have to catch the exception which is thrown by the throws
keyword.
Programmer has to handle the thrown exception.
It can throws checked exception.
All other exceptions that a method can throw must be declared in the throws clause.
The throws keyword must be followed by Throwable class or one of its subclasses.
This is the general form of a method declaration that includes a throws clause:
catch(ArithmeticException e)
{
System.out.println("Please Enter Valid Data");
}
}
}
Finally
Page 8 of 23
Finally creates a block of code that will be executed after a try/catch block has completed.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement matches
the exception.
The finally clause is optional. The finally block follows a try block or a catch block.
Syntax:
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
finally
{
// The finally block always executes.
}
Example:
class AE
{
public static void main(String args[])
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e) // catch divide-by-zero error
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("The finally statement is executed");
}
System.out.println("After catch statement.");
}
}
Page 9 of 23
Difference between throw and throws
Sr. throw throws
no.
1) throw keyword is used to explicitly throws keyword is used to declare an exception.
throw an exception.
3) Throw is used within the method. Throws is used with the method signature.
4) You cannot throw multiple exceptions. You can declare multiple exceptions.
5) Used only to throw but can not Throws is used to propagate exception to the
propagate exception to the calling calling method.
method.
6) Throw is followed by an instance. Throws is followed by class.
7) Public void m1() Public void m1() throws ArithmeticException
{ {
Throw new ArithmeticException();
} }
Built-in Exceptions
Que:
1. List any four inbuilt exceptions.
2. List four different inbuilt exceptions of Java.
Ans:
Built-in exceptions are the exceptions which are available in Java libraries.
Following is the list of Java Checked Exceptions:
1
ArithmeticException
Arithmetic error, such as divide-by-zero.
2
ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3
ArrayStoreException
Assignment to an array element of an incompatible type.
4
ClassCastException
Page 10 of 23
Invalid cast.
5
IllegalArgumentException
Illegal argument used to invoke a method.
6
IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.
7
IllegalStateException
Environment or application is in incorrect state.
8
IllegalThreadStateException
Requested operation not compatible with the current thread state.
9
IndexOutOfBoundsException
Some type of index is out-of-bounds.
10
NegativeArraySizeException
Array created with a negative size.
11
NullPointerException
Invalid use of a null reference.
12
NumberFormatException
Invalid conversion of a string to a numeric format.
13
SecurityException
Attempt to violate security.
14
StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
15
UnsupportedOperationException
An unsupported operation was encountered.
2
CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.
3
IllegalAccessException
Access to a class is denied.
4
InstantiationException
Attempt to create an object of an abstract class or interface.
5
InterruptedException
One thread has been interrupted by another thread.
6
NoSuchFieldException
A requested field does not exist.
7
NoSuchMethodException
A requested method does not exist.
User-Defined Exception
Java provides us facility to create our own exceptions which are basically derived classes
of Exception.
For example:
class ThrowExcep
{
static void div() throws MyException
{
int a=2,b=0;
if(b==0)
Page 12 of 23
throw new MyException("demo");
else
{
int ar=a/b;
}
}
public static void main(String args[])
{
try
{
div();
}
catch(MyException e)
{
System.out.println("Divide");
}
}
}
Main thread in Java
Que:
1. Define Thread in Java.
2. Define thread. State two ways to create a thread.
3. Explain ‘Extending Thread class’ in Java.
4. What is Thread? List different methods used to create Thread. Explain Thread life cycle.
Ans:
Java provides built-in support for multithreaded programming. A multi-threaded program
contains two or more thread that can run concurrently.
Definition:
Thread can be called lightweight process. Thread requires less resources to create and
exists in the process, thread shares the process resources.
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 spawned.
Often, it must be the last thread to finish execution because it performs various shutdown
actions.
Creating Thread
Page 13 of 23
1) Implementing Runnable Interface
To implement Runnable interface, a class need only implement a single method called
run( ), which is declared like this:
public void run( );
Inside run( ), we will define the code that constitutes the new thread.
To execute the run() method by a thread, pass an instance of ABC to a Thread in its
constructor.
Example:
class ABC implements Runnable
{
public void run()
{
System.out.println("ABC running");
}
}
class ThreadRunnable
{
Public static void main(String args[])
{
ABC ob1=new ABC();
Thread t1 = new Thread(ob1);
t1.start();
}
}
When the thread is started it will call the run() method of the MyClass instance instead of
executing its own run() method.
The above example would print out the text “ABC running“.
class ThreadExtend
{
public static void main(String args[])
{
ABC t1 = new ABC();
t1.start();
}
}
When the run() method executes it will print out the text “ABC running“.
Multiple Threads
Our program can affect as many threads as it needs. Let’s see how we can create multiple
threads.
ABC(String str)
{
name=str;
Thread t1=new Thread(this);
t1.start();
}
public void run()
{
try
Page 15 of 23
{
for(int i=0;i<5;i++)
{
System.out.println(name + " is Running: "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}
class multiThread
{
public static void main(String args[])
{
ABC ob1=new ABC("Thread1");
ABC ob2=new ABC("Thread2");
String name;
ABC(String str)
{
name=str;
start();
try
{
for(int i=0;i<5;i++)
{
Page 16 of 23
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}
class multiThread
{
public static void main(String args[])
{
ABC ob1=new ABC("Thread1");
ABC ob2=new ABC("Thread2");
}
}
Que:
1. Explain life cycle of a thread.
2. Explain life cycle of thread in Java.
3. Describe the complete life cycle of a thread.
Ans:
Following diagram shows Life Cycle of Thread.
New:
o The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
Page 17 of 23
Runnable:
o The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
Running:
o The thread is in running state if the thread scheduler has selected it.
Waiting:
o Sometimes a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
Terminated:
o A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Thread Priority
Que:
1. Explain thread priorities with suitable example.
2. List different thread priorities.
3. How do we set priorities for thread?
Ans:
1. public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for
this is 1.
2. public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly
define it. Value for this is 5.
3. public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.
class ThreadExtend
{
public static void main(String args[])
{
ABC t1 = new ABC();
t1.start();
System.out.println(t1.getPriority());
t1.setPriority(2);
System.out.println(t1.getPriority());
System.out.println(Thread.currentThread().getName());
}
Synchronization
Que:
1. Explain Synchronization in Thread.
2. What is Synchronization? When do we use it?
3. Explain thread synchronization.
Ans:
When two or more threads need access to a shared resource,they need some way to
ensure that the resource will be used by only one thread at a time. The by which this is
achieved is called Synchronization.
There are two way to achieve synchronizarion
Example:
class XYZ
{
Page 19 of 23
synchronized public void display(String name)
{
try
{
for(int i=0;i<5;i++)
{
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}
String name;
XYZ syob1;
syob1.display(name);
}
}
class SyncMethodThread
{
public static void main(String args[])
Page 20 of 23
{
XYZ syob1=new XYZ();
class XYZ
{
public void display(String name)
{
try
{
for(int i=0;i<5;i++)
{
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}
String name;
XYZ syob1;
Page 21 of 23
ABC(XYZ ob1,String str)
{
syob1=ob1;
name=str;
start();
synchronized(syob1)
{
syob1.display(name);
}
}
}
class SyncThread
{
public static void main(String args[])
{
XYZ syob1=new XYZ();
}
}
Method Description
Page 22 of 23
Method Description
Page 23 of 23