Depending on the Compiller, will verify the exception at compile time or not, the exception is divided into the following types:
1. Checked/ compileTime Exception
2. Unchecked/Runtime Exception
1) CheckedException:
It is also known as compileTime Exception. If you are using any java statement and if the statement may cause any exception then if it is verified by the compiler and if the compiler is forcing you to handle or to define as method level then these exceptions are known as checked exceptions.
These type of exception must be handled or must be defined as method level . if you are not performing any of this then compiler will generate compilation error with the following message
Unhandled Exception <Exception Name>
In java all the Exception classes that is the subclass of java.lang.Exception except(java.lang.RuntimeException and its subclass) are checked Exception.
package com.manish.exception;
import java.io.*;
public class Test2
{
public static void main(String[] args)throws IOException
{
System.out.println("main started");
FileInputStream fis=new FileInputStream("D://java");
System.out.println("main completed");
}
}
Unchecked Exception:
• These are known as RuntimeException.
• If You are defining any statement that may cause the exceptions and if may
not be verified by the compiler then it will be unchecked exception.
• For unchecked Exception if you want you can handle or you can define as
method level or you can ignore the exception.
• In java java.lang.RuntimeException and its subclass are checked exception--
package com.manish;
import java.io.*;
public class Test2
{
public static void main(String[] args)throws IOException
{
System.out.println("main started");
int x=10/0; //throws java.lang.RuntimeException
System.out.println("main completed");
}
}
Note:
Exception will not be thrown by the compiler while compiling source file. Compiler will only verify that you have any implementation to process the exception or not.
Exception will always be thrown by the JVM at Runtime.
To verify that the exception is checked or unchecked:
• If compiler will force to handle.
• By verifying the hierarchy
• By using the instance of RuntimeException.
package com.manish;
import java.io.*;
public class Test2
{
public static void main(String[] args)
{
Exception ex1=new ClassNotFoundException();
Exception ex2=new NullPointerException();
System.out.println(ex1 instanceof RuntimeException);
//false
}
}
Q.What will happen if you try to compile or execute the following code ?
Ans: By using the threading concept JVM will process the task. After verifying the class and the required main method JVM will invoke the main method.
JVM will process the statements available in the method one by one:
Case 1:
If no value provided as CLA then java.lang.ArrayIndexOutOfBoundsException
will occur.
Case2:
If value provided as CLA then
Will be stored in data variable
Try to convert into int type
If the specified value is not int type then java.lang.NumberFormatException
will occur
Case 3:
If the specified value is int type then
Will be converted and stored in the x variable.
Divide the 10 value with x
If x value is non-zero then result will be accessed and will be displayed.
If the x value is zero ArithmeticException will occur
Exception will occur means:
Identifying the problem.
Verifying the class define in the java language.
Create the object of the verified class.
Throw the object
Once the object will be thrown(event generated) JVM will verify that any statement in your current scope to catch the thrown object.
If no statement found then control will be transferred to the caller method. In this condition the caller of the main is JVM . If JVM will handle the exception then program execution will be terminated.
If you want to catch the exception explicitly so that the other statement from your application can be executed successfully then you need to use the exception handler.
In java try catch statement will be used as Exception handler.
Syntax 1:
try
{
}
catch(<Throwable Type> <ref variable>)
{
}
Syntax 2:
try
{
}
catch(<Throwable Type> <ref variable>)
{
}
catch(<Throwable Type> <ref variable>)
{
}
Syntax 3:
try
{
}
catch(<Throwable Type> <ref variable>)
{
}
finally
{
}
Syntax 4:
try
{
}
finally
{
}
Statement 1
try
{
Statement 2
Statement 3
Statement 4
}
catch(<Throwable Type> <ref variable>)
{
Statement 5
Statement 6
}
Statement 7
Statement 8
• The statement that may cause the problem is always placed inside the try
block.
• Inside the catch block you can place the statements that will be executed if
the corresponding problem occurred.
• In the above case(syntax 4 block) if statement 1 throws any exception then it
will not be handled.
• if statement 5,6,7,8 throws any exception then it will not be handled.
• If statement 2,3,4 executed successfully then catch block will not be executed.
Control will be transferred after catch block(statement 7).
• If statement 3 throws any exception then catch block will be executed. After
executing the catch block control will be transferred after catch (i.e. statement 7). Statement 4 will not be executed.
• The statement available in the try block may throw the exception and it can be
caught by the catch block then it will be handled.
• If the exception will be thrown because of the statement available before the
try, within the catch or after try catch then those exceptions will not be
handled.
• If any exception occurred from the try block then other statement available in
the try block will not be executed(not after handling the exception also).
Note:
If you are handling the exception then you can display the message that can be understood by the end user.
Q. Write a program to read one int value as CLA, divide 10 by specified value and display result?Handle the exception if occurred.
package com.manish;
public class EXTest3
{
public static void main(String[] args)
{
System.out.println("main started");
try
{
String data=args[0];
int x=Integer.parseInt(data);
int res=10/x;
System.out.println("result "+res);
}
catch(Exception e)
{
if(e instanceof ArrayIndexOutOfBoundsException)
{
System.out.println("provide one value as CLA");
}
else if(e instanceof NumberFormatException)
{
System.out.println("provide one int value as CLA");
}
else if(e instanceof ArithmeticException)
{
System.out.println("provide non-zero int value as CLA");
}
}
System.out.println("main completed");
}
}
• If you are defining some statement in the try block then statement may cause
various types of exception in various conditions. To handle all the possible
exception you can define the super type in the catch block and by using else if
else statement in the catch block you can verify the actual exception type.
• Instead of defining if else if in catch block you can define multiple catch block
for one try block.
• If you are defining multiple catch block then you need to follow the following
rules.
1. The exception names in the multiple catch block must be unique.
2. If the exception type don’t have any inheritance relation then the order for the catch can be any order.
3. If the exception type has some inheritance relation then first you need to define the subtype exception then the super type exception.
Note:
If you are using multiple catch block for one try block then when the exception will be thrown the exception type defined in the catch block will be verified in the order in which it is defined. If matching catch will be found that block will be executed and after that other catch block will not be verified and will not be executed.
If matching catch block is not be found then exception will not be handle and
control will return to the caller of the method.
Refer Lab2
Note:
• When defining the catch block if you are specifying some exception i.e unchecked exception and if no statement available in the try block that may cause that exception then compiler won’t generate any error.
try
{
int res=10/0;
}
catch(NullPointerException ex)
{
……
}
• If you are defining any checked exception that will not be thrown by the try block then compiler will generate compilation error.
try
{
int res=10/0;
}
catch(ClassNotFoundException ex)
{
……
}
• You can define multiple try catch statement in one block (method etc).
Finally Block:
• If you are using try block and catch statement then for some requirement you
want to execute some statement in any condition.
• In some scenario if you want to use try and you don’t want to handle the
exception but you want to use some statement in any condition then you can
use finally block.
• If no exception will be thrown from the try block then finally block will be
executed.
• If exception will be thrown from the try block and if it will be handle then after
the catch block finally block will be executed.
• If try is throwing the exception that is not handle then before returning the
control to the caller finally block will be executed.
• If any return statement available in the try or catch block then before
returning the control finally block will be executed.
• Normally the finally block will be used to close the resource like database
connection, IO connection, network connection etc.(will be discussed in jdbc topic).
Note:
If the JVM will be terminated before executing the finally block then finally block will not be executed.
By using the following statement you can terminate the JVM explicitly.
System.exit(0);
Q. What is the difference between finally and finalize?
The task of finalize() method is similar to the finally block. If the variable(resource) you are defining in the class as the instance member then you can release using the finalize ()method.
If the resource you are defining within the member of the class then that member cannot be used from the finalize(). To release the local resources you can use the finally block.
Case 1:
package com.manish;
import java.sql.*;
public class Ctest4
{
public static void main(String[] args)
{
}
}
class Service
{
Connection con=null;
public void service()
{
//statement
}
public void add()
{
//statement
}
protected void finalize()throws SQLException
{
con.close();
}
}
Case 2:
package com.jlcindia;
import java.sql.*;
public class Ctest4
{
public static void main(String[] args)
{
}
}
class Service
{
public void service()
{
//statement
}
public void add()
{
Connection con=null;
try
{
}
catch(Exception e)
{
}
finally
{
try
{
con.close();
}catch(Exception e)
{
}
}
}
protected void finalize()throws SQLException
{
// con.close();
}
}
Q. How many finally block can be used with one try block?
Ans: Only one.
Q. How many catch block can we use with one try block?
Ans: Any number.
Q. Can you define multiple try block for one catch block?
Ans: No
Q. Can you define any other statements between try and catch, try and finally, catch and finally?
Ans: No
Q. Can you define finally block after try block but before catch block?
Ans: No
Q. can you use try block without catch block?
Ans: Yes, but finally block will be used.
Q. if you are defining try and finally without catch then if exception occurred in try, it will be handled or not?
Ans: No
Q. Can you define any try-catch-finally inside the try-catch or finally block?
Ans: Yes
Q. When you can define the try -catch block inside the catch/ finally?
Ans: if the statement in the catch or finally is throwing the exception and if you want to handle the exception.
Q. Can you define multiple try- catch block in one method?
Ans: yes
Q. What will be returned to the caller if statement from the finally block will throw the exception that is not handle?
Ans: The same exception will be returned from the caller.
Q. what will be the result of the following code?
Ans:
package com.jlcindia;
public class ExTest6
{
public static void main(String[] args)
{
System.out.println("main started");
int r=0;
r=Op.getResult(2);
System.out.println("in main:"+r);
r=Op.getResult(-2);
System.out.println("in main: "+r);
}
}
class Op
{
static int getResult(int x)
{
int res=-1;
try
{
int arr[]=new int[x];
res=90;
System.out.println("in try: "+res);
return res;
}catch(NegativeArraySizeException e)
{
res=77;
System.out.println("catch: "+res);
return res;
}
finally
{
res=9898;
System.out.println("finally: "+res);
}
}
}
Output:
main started
in try: 90
finally: 9898
in main:90
catch: 77
finally: 9898
in main: 77
Q. what will be the result of the following code?
Ans:
package com.manish;
public class ExTest6
{
public static void main(String[] args)
{
System.out.println("main started");
int r=0;
r=Op.getResult(2);
System.out.println("in main:"+r);
r=Op.getResult(-2);
System.out.println("in main: "+r);
}
}
class Op
{
static int getResult(int x)
{
int res=-1;
try
{
int arr[]=new int[x];
res=90;
System.out.println("in try: "+res);
return res;
}catch(NegativeArraySizeException e)
{
res=77;
System.out.println("catch: "+res);
return res;
}
finally
{
res=9898;
System.out.println("finally: "+res);
return res;
}
}
}
Output:
main started
in try: 90
finally: 9898
in main:9898
catch: 77
finally: 9898
in main: 9898
The methods that can be used with the object of Throwable type:
• To access the message available with the exception
Public void String getMessage()
• To get the reason of the exception if available
Public Throwable getCause()
• To print the stack trace to the default device or console
Public void printStackTrace()
• To print the stack trace to the specified printStream(File/Network etc.)
Public void printStackTrace(PrintStream ps)
• To print the stack trace to the specified printWriter(File/Network etc.)
Public void printStackTrace(PrintWriter pw)
• To initialize the reason for the exception
Public void initCause(Throwable cause)
Note:
toString() method is overridden in the Throwable class to return the String as
<fullyQualifiedClassName> : <message>
getClass().getName()+ ”:”+getMessage()
User defined Exception/ Custom Exception:
• In java vendor has provided various types of exceptions for various reasons.
• If you are developing any application then you may get some requirement to
instruct the user (who is going to use your method or constructor) about the
problem occurred while executing the statement.
• If you want to instruct then you need to define some exception for your
requirement. In java you can define custom exception if required.
To define the custom exceptions you can follow the following steps:
1). Write a java class by extending any predefined exception. It is
recommendable to extend either java.lang.Exception or
java.lang.RuntimeException.
2). If you are extending java.lang.Exception then the custom exception will be
checked exception.
3). If you are extending java.lang.RuntimeException then the custom exception
will be unchecked exception.
4). If you want to store some data then you can define some variable and to
initialize the variable you can define some constructor.
5). To initialize the message for the exception you can invoke the super
constructor with String parameter.
6). You can override the method inherited from the super class.
class EmptySidException extends Exception{}
class InvalidIdException extends RuntimeException
{
InvalidIdException(String id)
{
super(id);
}
}
Throw keyword:
• Throw is a keyword defined that will be used to throw the exception explicitly.
• You can throw any checked or unchecked exception.
• You can throw any built-in or user defined exception.
Syntax:
Throw < throwableTypeObjectRef >
Throw new NullPointerException()
Throw new EmptySidException()
Throw new InvalidIdException(“SD-009”);
Q. What is the difference between return and throw?
Ans: In the case of return the control will be returned to the caller and the other statement of the caller method will be executed successful.
No comments:
Post a Comment