Java Unit4
Java Unit4
Unit – IV:
Types of errors
Example:
class ExError
{
public static void main(String args[])
{
System.out.println(“Preeti Gajjar”) //Missing semicolon
Prepared By: Department of Computer Engineering Page 1
Subject Name: Advanced Object Oriented Programming Unit No: 04 Subject Code: 4340701
}
}
Output:
Javac detects an error and display it as follow: Error1.java: 5: „;
„expected System.out.println (“Preeti Gajjar”)
^1 error
System.out.println(“Result=”+c);
}
}
Output:
Result= 5 instead of 15
Exception Hierarchy
All exception and error types are subclasses of class Throwable, which is the base class of the
hierarchy.
Immediately below Throwable, are two subclasses that partition exceptions into two distinct branches.
o Exception Class :
One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch.
Ex.NullPointerException is an example of such an exception.
o Error Class
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).
Ex.StackOverflowError is an example of such an error.
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked
exception. However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions
are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
o The try statement allows you to define a block of code to be tested for errors while it is being executed.
o The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.
o The try and catch keywords come in pairs:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Example:
class TryCatchEx
{
public static void main(String args[])
{
try
{
int a=10,b=0;
int x = a / b; // Arithmetic exception
System.out.println(“Result=” +c);
}
catch(ArithmeticException e)
{
System.out.println(“Caught an exception:” + e.getMessage());
}
System.out.println(“End of the program”); //This line will execute
}
}
Output:
throw keyword:
o We can make a program to throw an exception explicitly using throw statement.
o throw throwableInstance;
o throw keyword throws a new exception.
o An object of class that extends throwable can be thrown and caught.
o Throwable ->Exception -> MyException
o The flow of execution stops immediately after the throw statement ;
o Any subsequent statements are not executed. the nearest enclosing try block is inspected to
see if it has catch statement that matches the type of exception.
o If it matches, control is transferred to that statement
o If it doesn‟t match, then the next enclosing try statement is inspected and so on. If no catch
block is matched than default exception handler halts the program.
o Syntax:
throw new thowable_instance;
o Example:
throw new ArithmeticException ();
throw new MyException();
Here ,new is used to construct an instance of MyException().
All java‟s runtime exception s have at least two constructors:
1) One with no parameter
2) One that takes a string parameter.
In that the argument specifies a string that describe the exception. this string is displayed when
object as used as an argument to print() or println() .
It can also obtained by a call to getMessage(),a method defined by Throwable class.
Example:
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":
}
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...)
}
}
Output:
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)
throws keywords
o The Java throws keyword is used to declare an exception.
o It gives an information to the programmer that there may occur an exception.
o So, it is better for the programmer to provide the exception handling code so that the normal flow of
the program can be maintained.
o Exception Handling is mainly used to handle the checked exceptions.
o If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that
he is not checking the code before it being used.
o Syntax:
return_type method_name() throws exception_class_name{
//method code
}
o Example:
import java.io.IOException;
class Testthrows1{
void m() throws IOException{
throw new IOException("device error");//checked exception
}
void n() throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
}
}
Output:
exception handled
normal flow...
finally clause
It can be used to handle an exception that is not caught by any of the previous catch statements.
It can be used to handle any exception generated within a try block.
It may be added immediately after try block or after the last catch block.
finally block is guaranteed to execute if no any exception is thrown.
Use:
1. closing file , record set
2. closing the connection with database
3. releasing system resources
4. releasing fonts
5. Terminating network connections, printer connection etc.
6.
We can use finally in this two way.
Syntax:1
try
{
…………..
}
finally
{
……………...
}
Syntax:2
try
{
………..
}
catch(…….)
{
…………….
}
catch (…….)
{
………..
}
finally
{
……………
}
Example:
class finallyEx {
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.
Uses of 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
Example:
{
rollno = a ;
}
public String toString()
{
return “MyException[” + rollno + “] is less than zero”;
}
}
class Student
{
Static void sum(int a, int b) throws std
{
if(a<0)
{
throw new std(a); //throws user defined exception object
}
else
{
System.out.println(a+b);
}
}
public static void main(String[] args)
{
try
{
sum(-10,10);
}
catch(std me)
{
System.out.println(me);
}
}
}
Output:
Concept of Multithreading
Multithreading is a conceptual programming paradigm where a program (or process) is divided
into two or more subprograms(or process),which can be implemented at the same time in parallel.
Threads in java are subprograms of main application program and share the same memory space.
Multithreading is similar to dividing a task into subtasks and assigning them to different people
for execution independently and simultaneously, to achieve a single desire.
We use multithreading than multiprocessing because threads use a shared memory area.
It is mostly used in games, animation, etc.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Concept of thread
A thread is executed along with its several operations within a single process as shown in figure below:
Single Process
Operation 1
Thread 1
Operation 2
…….
Operation N
A multithreaded programs contain two or more threads that can run concurrently.
Threads share the same data and code.
MultiThreading Concept
Thread 1 Thread 2
Operation 1
Operation 1
Operation 2 Operation 2
…….
…….
Operation N
Operation N
Creating thread
To execute a thread, it is first created and then start() method is invoked on the thread. Then thread would
execute and run method would be invoked.
During the life time of a thread ,there are many states it can enter, They are:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
A thread is always in one of these five states. It can move from one state to another via a variety of ways.
3) Running state
The processor has given its time to the thread for its execution.
The thread runs until it relinquishes control on its own or it is preempted by a higher priority
thread.
A running thread may change its state to another state in one of the following situations.
1) When It has been suspended using suspend( ) method.
2) It has been made to sleep( ).
3) When it has been told to wait until some events occurs.
4) Blocked state/ Waiting
• A thread is waiting for another thread to perform a task. The thread is still alive.
• A blocked thread is considered “not runnable” but not dead and so fully qualified to run again.
5) Dead state/ Terminated
• Every thread has a life cycle. A running thread ends its life when it has completed executing its
run ( ) method.
• It is natural death. However we can kill it by sending the stop message.
• A thread can be killed as soon it is born or while it is running or even when it is in “blocked”
condition.
Thread class’s methods:
Thread priority
Every thread in java has its own priority.
Thread priority are used by thread scheduler to decide when each thread should be allowed to run.
In Java, thread priority ranges between:
o MIN-PRIORITY( a contant of 1 )
o MAX-PRIORITY( a contant of 10 )
o NORM-PRIORITY (a contant of 5) , it is default.
Example:
When we create a thread start() method performs some internal process and then calls run() method.
The start() method does not start another thread of control but run() is not really “main” method of new
thread.
All uncaught exceptions are handled by code outside the run() method before the thread terminates.
It is possible for a program to write a new default exception handler.
The default exception handler is the uncaughtException method of the Thread group class.
Whenever uncaught exception occurs in thread’s run method, we get a default exception dump which gets
printed on System.err stream.
Example:
class MyThread extends Thread{
public void run(){
System.out.println("Throwing in " +"MyThread");
throw new RuntimeException();
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
try {
Thread.sleep(1000);
} catch (Exception x) {
System.out.println("Caught it" + x);
}
System.out.println("Exiting main");
}
}
Output:
Throwing in MyThread
Exception in thread "Thread-0" java.lang.RuntimeException
at testapp.MyThread.run(Main.java:19)
Exiting main