Java Exceptions
Java Exceptions
disrupts its normal flow. Java provides a robust and object-oriented way to handle
exception scenarios known as Java Exception Handling.
Exceptions in Java can arise from different kinds of situations such as wrong data
entered by the user, hardware failure, network connection failure, or a database server
that is down.
Java creates an exception object when an error occurs while executing a statement.
The exception object contains a lot of debugging information such as method
hierarchy, line number where the exception occurred, and type of exception.
If an exception occurs in a method, the process of creating the exception object and
handing it over to the runtime environment is called “throwing the exception
Java Exception handling framework is used to handle runtime errors only. The
compile-time errors have to be fixed by the developer writing the code else the
program won’t execute.
1. Errors: Errors are exceptional scenarios that are out of the scope of
application, and it’s not possible to anticipate and recover from them. For example,
hardware failure, Java virtual machine (JVM) crash, or out-of-memory error. That’s
why we have a separate hierarchy of Errors and we should not try to handle these
situations. Some of the common Errors
are OutOfMemoryError and StackOverflowError.
2. Checked Exceptions: Checked Exceptions are exceptional scenarios that we
can anticipate in a program and try to recover from it. For
example, FileNotFoundException. We should catch this exception and provide a
useful message to the user and log it properly for debugging purposes.
The Exception is the parent class of all Checked Exceptions. If we are throwing a
Checked Exception, we must catch it in the same method, or we have to propagate it
to the caller using the throws keyword.
3. Runtime Exception: Runtime Exceptions are caused by bad programming.
For example, trying to retrieve an element from an array. We should check the length
of the array first before trying to retrieve the element otherwise it might
throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the parent
class of all Runtime Exceptions. If we are throwing any Runtime Exception in a
method, it’s not required to specify them in the method signature throws clause.
Runtime exceptions can be avoided with better programming.
What is Exception? Explain the steps to create your own exception with a suitable
example.
Exception in Java:
An Exception is an unwanted event that interrupts the normal flow of program.
When an exception occurs program execution gets terminated. In such case we get
a system generated error message.
The good thing about exception is that they can be handled in Java.
By handling the exception we can provide a meaningful message to the user about
the issue rather than a system generated message, which may not be
understandable to a user.
A Java exception is an object that describes an exceptional condition that has
occurred in a piece of code.
Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code.
Exception Handling:
Exception handling is one of the most important feature of java programming
that allow us to handle the runtime errors caused by exception.
Creating User Defined Exceotions:
If you are creating your own Exception that is known as custom exception or user
defined exception. Java custom exceptions are used to customize the exception
according to user need.
By the help of custom exception, you can have your own exception and message.
Let's see a simple example of java custom exception:
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException1
{
static void validate (int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try
{
validate (13);
}
catch(Exception m)
{
System.out.println ("Exception occured: "+m);
}
System.out.println ("rest of the code...");
}
}
Output:
Output:Exceptionoccured: InvalidAgeException:not valid
rest of the code.
Q.2 Explain how Exception handling is done in java. Write a program to
demonstrate use of throw and throws keyword.
Q.3 Which are the types of Exception? Explain try, catch, throw & throws keyword.
Exception Handling:
Exception handling is one of the most important feature of java programming
that allow us to handle the runtime errors caused by exception.
Exception Types in Java:
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception.
The sun micro system says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Exception Types in Java
1) Checked exceptions:
A checked exception is an exception that occurs at the compile time, these are also
called as compile time exceptions.
These exceptions cannot simply be ignored at the time of compilation, the
programmer should take care of (handle) these 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.
Examples of Checked Exception:
1. ClassNotFoundException
2. IllegalAccesssException
3. NoSuchFieldException
4. EOFException etc.
2) Unchecked exceptions:
An unchecked exception is an exception that occurs at the time of execution. These
are also called as Runtime Exceptions.
These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
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 ArrayIndexOutOfBoundsExceptioexception
occurs.
Examples of Checked Exception:
1. ArithmeticException
2. ArrayIndexOutOfBounds Exception
3. NullPointerException
4. NegativeArraySizeException
5. NumberFormatException
6. SecurityException etc.
3) Errors:
These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer.
Errors are typically ignored in your code because you can rarely do anything about
an error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at
the time of compilation.
Exception Keyword in Java:
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
1) Java try block:
The try block contains set of statements where an exception can occur.
A try block is always followed by a catch block, which handles the exception that
occurs in associated try block.
It must be used within the method.
Java try block must be followed by catch or finally block or both.
Syntax of try block:
try
{
//statements that may cause an exception
}
try
{
//statements that may cause an exception
}
2) Java catch block
Java catch block is used to handle the Exception. It must be used after the try block
only.
You can use multiple catch block with a single try.
You can catch different exception in different catch block.
When an exception occurs in try block, the corresponding catch block that handles
that particular exception executes.
For example if an arithmetic exception occurs in try block then the statements
enclosed in catch block for arithmetic exception executes.
Syntax of try catch in java:
try
{
//statements that may cause an exception
}
catch(exception(type) e(object))
{
//error handling code
}
3) Java finally block:
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Java finally block is always executed whether exception is handled or not.
The finally block follows a try block or a catch block.
A finally block of code always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want
to
execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks.
Syntax of finally block:
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
finally
{
//Statements to be executed
}
4) Java throw keyword:
The Java throw keyword is used to explicitly throw an exception.
In order to throw user defined exception, throw keyword is being used.
We can also throw an already defined exception like ArithmeticException,
IOException etc.
We can throw either checked or unchecked exception in java by throw keyword.
The throw keyword is mainly used to throw custom exception.
Syntax of throw keyword:
Throw new exception_class (“error message”);
For example:
throw new ArithmeticException (“dividing a number by 5 is not allowed in this
program”);
Java throw keyword example:
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.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid Unit-5 Exception
5) Java throws keyword:
The Java throws keyword is used to declare an exception.
It gives an information to the programmer that there may occur an exception so it
is better for the programmer to provide the exception handling code so that normal
flow can be maintained.
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 performing check up before the code being used.
It provides information to the caller of the method about the exception.
Syntax of java throws:
return_type method_name() throws exception_class_name
{
//method code
}
Java throws example:
Let's see the example of java throws clause which describes that checked
exceptions
can be propagated by throws keyword.
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...");
}
}
Output:
exception handled
normal flow...
Q.4 Define an exception called "No Match Exception" that is thrown when a string
is not equal to "Mumbai". Write a program that uses this Exception.
No Match Exception Program Example:
import java.io.DataInputStream;
import java.io.IOException;
public class NoMatchException extends Exception
{
public static void main(String args[])
{
String s = new String();
DataInputStream in = new DataInputStream(System.in);
try
{
System.out.println("Enter the String:");
s = in.readLine();
}
catch(IOException nme)
{}
try
{
if(s.equals("India"))
{
throw new NoMatchException();
}
}
catch(NoMatchException nme)
{
System.out.println("No Match Exception Caught: " +nme);
}
}
Q.5 Write java Exception handling program to demonstrate any two java's
unchecked
Runtime exception subclasses.
Unchecked exceptions:
An unchecked exception is an exception that occurs at the time of execution. These
are also called as Runtime Exceptions.
These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
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 ArrayIndexOutOfBoundsException exception
occurs.
Examples of Checked Exception:
1. ArithmeticException
2. ArrayIndexOutOfBounds Exception
3. NullPointerException
4. NegativeArraySizeException
5. NumberFormatException
6. SecurityException etc.
Arithmetic Exception Example:
class Demo
{
public static void main (String [] args)
{
try
{
Int c = 10/0;
System.out.println (“The value is”+c);
}
catch (Arithmetic Exception e)
{
System.out.println (e);
}
finally
{
System.out.println (“I will be executed always”);
}
}
}