Unit3 first half
Unit3 first half
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.
Exception:
Definition:1 A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.
Definition:2In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
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 need to handle
exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest
of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we
perform exception handling, the rest of the statements will be executed. That is why we use exception
handling in Java
.
Hierarchy of Java Exception classes
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the
exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions
into two distinct branches. One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. This is also the class that you will subclass to create your
own custom exception types. There is an important subclass of Exception, called RuntimeException.
Exceptions of this type are automatically defined for the programs that you write and include things
such as division by zero and invalid array indexing. The other branch is topped by Error, which defines
exceptions that are not expected to be caught under normal circumstances by your program. Exceptions
of type Error are used by the Java run-time system to indicate errors having to do with the run-time
environment, itself. Stack overflow 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.
1. Checked Exception
2. Unchecked Exception
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.
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.
Keywor Description
d
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.
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.
Java Exception Handling Example
Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
JavaExceptionExample.java
1.
2. public class JavaExceptionExample{
3. public static void main(String args[]){
4. try{
5. //code that may raise exception
6. int data=100/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8. //rest code of the program
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string
variable that has characters; converting this variable into digit will cause NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
If an exception occurs at the particular statement in the try block, the rest of the block code will not
execute. So, it is recommended not to keep the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
The catch block must be used after the try block only. You can use multiple catch block with a single
try block.
Points to remember
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
MultipleCatchBlock1.java
Output:
Example 2
MultipleCatchBlock2.java
Output:
In this example, try block contains two exceptions. But at a time only one exception occurs and its
corresponding catch block is executed.
Example 3
In this example, we generate NullPointerException, but didn't provide the corresponding exception
type. In such case, the catch block containing the parent exception class Exception will invoked.
MultipleCatchBlock4.java
Output:
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while
the outer try block can handle the ArithemeticException (division by zero).
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
NestedTryBlock.java
System.out.println("normal flow..");
}
}
Output:
When any try block does not have a catch block for a particular exception, then the catch block of the
outer (parent) try block are checked for that exception, and if it matches, the catch block of outer try
block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the Java
runtime system will handle the exception. Then it displays the system generated message for that
exception.
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.
Example:
Let's see the following example where the Java code throws an exception and the catch block handles
the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code
is also executed normally.
TestFinallyBlock2.java
try {
Output:
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to
throw a custom exception. We will discuss custom exceptions later in this section.
We can also define our own set of conditions and throw an exception explicitly using throw keyword.
For example, we can throw ArithmeticException if we divide a number by another number. Here, we
just need to set the condition and throw exception using throw keyword.
In this example, we have created a method named validate() that accepts an integer as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome
to vote.
TestThrow1.java
In this example, we have created the validate method that takes integer value as a parameter. If the
age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to
vote.
Output:
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception or declare in throws clause.
If we throw a checked exception using throw keyword, it is must to handle the exception using catch
block or the method must declare it using throws declaration.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers' fault that he is not checking the code
before it being used.
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");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Test it Now
Output:
exception handled
normal flow...
The following are the important differences between throw and throws.
Definition Throw is a keyword which is used Throws is a keyword used in the method
to throw an exception explicitly in signature used to declare an exception
1
the program inside a function or which might get thrown by the function
inside a block of code. while executing the code.
Type of With throw keyword we can On other hand with throws keyword both
exception propagate only unchecked checked and unchecked exceptions can be
3 exception i.e checked exception declared and for the propagation checked
cannot be propagated using exception must use throws keyword
throw. followed by specific exception class name.
Syntax Syntax wise throw keyword is On other hand syntax wise throws keyword
4
followed by the instance variable. is followed by exception class names.
Declaration In order to use throw keyword we On other hand throws keyword is used with
5 should know that throw keyword the method signature.
is used within the method.
Java Built-in Exception
In the language of Java, these are called unchecked exceptions because the compiler does
not check to see if a method handles or throws these exceptions. The unchecked exceptions
defined in java.lang are listed in Table 10-1 . Table 10-2 lists those exceptions defined by
java.lang that must be included in a method’s throws list if that method can generate one of
these exceptions and does not handle it itself. These are called checked exceptions.
Java Custom Exception/User Defined Exception
In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our
own Exception is known as custom exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have passed a
string to the constructor of superclass i.e. Exception class that can be obtained using getMessage()
method on the object we have created.
In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.
Note: We need to write the constructor that takes the String as the error message and it is called parent class constructor.
Example 1:
Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of parent class
Exception using the super() method. Also the constructor of Exception class can be called without
using a parameter and calling super() method is not mandatory.
TestCustomException1.java
1. // class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
Output: