Exceptions
Exceptions
foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs.
These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the
programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
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.
1. throw – We know that if any exception occurs, an exception object is getting created and then
Java runtime starts processing to handle them. Sometime we might want to generate exception
explicitly in our code, for example in a user authentication program we should throw exception
to client if the password is null. throw keyword is used to throw exception to the runtime to
handle it.
2. throws – When we are throwing any exception in a method and not handling it, then we need to
use throws keyword in method signature to let caller program know the exceptions that might
be thrown by the method. The caller method might handle these exceptions or propagate it to
it’s caller method using throws keyword. We can provide multiple exceptions in the throws
clause and it can be used with main()method also.
3. try-catch – We use try-catch block for exception handling in our code. try is the start of the
block and catch is at the end of try block to handle the exceptions. We can have multiple catch
blocks with a try and try-catch block can be nested also. catch block requires a parameter that
should be of type Exception.
4. finally – finally block is optional and can be used only with try-catch block. Since exception
halts the process of execution, we might have some resources open that will not get closed, so
we can use finally block. finally block gets executed always, whether exception occurred or not.
Exception Description
Exception Description
You have used all your arrays and need to buy more from the array
ArrayStoreException
store.
You need to stay in the class or caste you were born into. Java will
not accept dailits acting as kshatriyas or noblemen pretending to
ClassCastException be working class. Note the spelling mistake (of caste) that was
introduced in Java 1.0 and has not been corrected for backwards
compatability reasons.
You seem to have invented your own class. There are also caste
systems that are not yet implemented in Java, most notibly the
ClassNotFoundException
balinese caste system. For example, if you are a wesia, use the
indian counterpart vaishya.
You are a clone. Find the original you, tell him what you want to do
CloneNotSupportedException
and then kill yourself.
You come from a state that is not yet recognized by the UN,
IllegalStateException possibly Kurdistan or Palestine. Get a real citizenship, recompile
your java code and try again.
One of the screws in your computer is threaded the wrong way.
IllegalThreadStateException
Please contact your hardware vendor.
Tell your colleagues, room-mates etc. to leave you alone while you
InterruptedException
are working.
You have created an array with negative size. This can cause
information to be lost and in the long run the Universe will be
NegativeArraySizeException
destroyed. Be happy that Java noticed what you were doing and
DON'T DO IT AGAIN.
You are trying to have a picknick on a field that does not exist. You
can also get this exception if you try to visit an airfield that in fact
NoSuchFieldException
does exist, but has been classified as top-secret. I'd give you
examples, but then I'd have to kill you.
NoSuchMethodException Don't use that method! Please, do things like we have always done.
You do not own a dog. Get one, for example a brittany spaniel, and
NullPointerException
try again.
You cannot run fast enough, possibly due to obesity. Turn off your
RuntimeException
computer and go out and get som exercise.
You have been deemed a threat to nationaly security. Please sit still
SecurityException
and wait for the authorities to come and get you.
Your panties have shiften out of place. Adjust them and try again.
StringIndexOutOfBoundsException You can also get this exception if you are not wearing any panties
at all.
You are trying to have an operation that for som reason, ethical or
otherwise, is not supported by Java. Examples of this include
UnsupportedOperationException
unneeded amputations, for example circumcisions. Please stop
abusing your body and do not remove pieces of you child, damn it!
java.util
java.awt
java.awt.color
Your CMM is broken. What ever the hell that is. I usually burn
CMMException
my house down and move to a new city to start over.
java.awt.datatransfer
java.io
java.net
You are making an urn and either it has the wrong shape
MalformedURLException (e.g. an "L" shape) or you have misspelled the word
"urn" (e.g. "url").
java.rmi
You are trying to use an object that does not exist. Create
NoSuchObjectException
it or don't use it, Einstein!
Tennis matches are long enough as it is. You will get this
ServerRuntimeException
exception if you take too long to serve.
When you go to the movies, you should always keep your
stub. If you don't, and also leave the theater, you will not
StubNotFoundException
be let back in and you may have to buy a new ticket. So,
KEEP YOUR STUB!
java.security
ParseException You are not making any sense. Calm down and try again.
before:
after:
another example:
import java.util.Scanner;
class Division {
public static void main(String[] args) {
int a, b, result;
a = input.nextInt();
b = input.nextInt();
result = a / b;
class Division {
public static void main(String[] args) {
int a, b, result;
a = input.nextInt();
b = input.nextInt();
// try block
try {
result = a / b;
System.out.println("Result = " + result);
}
// catch block
catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
}
}
class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
catch(Exception e5){
System.out.println("Exception");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement..");
}
}
Exception handling in Method
overriding
Rule: An overriding method (the method of child class) can throw anyunchecked
exceptions, regardless of whether the overridden method (method of base class) throws
exceptions or not. However the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw those checked exceptions, which have less scope than the
exception(s) declared in the overridden method.
If base class doesn’t throw any exception but child class throws an unchecked
exception.
In this example class Room is overriding the method color(). The overridden method is not
throwing any exception however the overriding method is throwing an unchecked exception
(NullPointerException). Upon compilation code ran successfully.
class Building {
void color()
{
System.out.println("Blue");
}
}
class Room extends Building{
//It throws an unchecked exception
void color() throws NullPointerException
{
System.out.println("White");
}
public static void main(String args[]){
Building obj = new Room();
obj.color();
}
}
If base class doesn’t throw any exception but child class throws an checked
exception
import java.io.*;
class Building {
void color()
{
System.out.println("Blue");
}
}
class Room extends Building{
void color() throws IOException
{
System.out.println("White");
}
public static void main(String args[]){
Building obj = new Room();
try{
obj.color();
}catch(Exception e){
System.out.println(e);
}
}
}
When base class and child class both throws a checked exception
import java.io.*;
class Building {
void color() throws IOException
{
System.out.println("Blue");
}
}
class Room extends Building{
void color() throws IOException
{
System.out.println("White");
}
public static void main(String args[]){
Building obj = new Room();
try{
obj.color();
}catch(Exception e){
System.out.println(e);
}
}
}
class EmployeeTest {
static void employeeAge(int age) throws MyOwnException{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args) {
try {
employeeAge(-2);
}
catch (MyOwnException e) {
e.printStackTrace();
}
}
}
ArrayIndexOutOfBounds Exception
Class: Java.lang.ArrayIndexOutOfBoundsException
This is a built in class present in java.lang package. This exception occurs when the
referenced element does not exist in the array.
class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
NumberFormat Exception
Class: Java.lang.NumberFormatException
The object of the above built-in class gets created whenever a string is parsed to any
numeric variable.
class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
StringIndexOutOfBound Exception
Class: Java.lang.StringIndexOutOfBoundsException
An object of this class gets created whenever an index is invoked of a string, which is not
in the range.
Each character of a string object is stored in a particular index starting from 0.
class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="easysteps2buildwebsite";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
NullPointer Exception
Class: Java.lang.NullPointer Exception
An object of this class gets created whenever a member is invoked with a “null” object.
class Exception2
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}
Summary
o Checked exceptions must be caught or forwarded. This can be done in a try ...
catch statement or by defining the exception in the method definition.
o The exception is caught by the first catch block whose associated exception class
matches the class or a superclass of the thrown exception.
o If no matching catch block is found in the exception chain, the thread containing the
thrown exception is terminated.
o The finally block after a try ... catch statement is executed regardless whether an
exception is caught or not.
o Returning within a finally block breaks the exception chain to the invoker even for
uncaught exceptions.