Sie sind auf Seite 1von 27

 Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be

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.

list of Java Unchecked RuntimeException.

Exception Description

ArithmeticException Arithmetic error, such as divide-by-zero.

ArrayIndexOutOfBoundsException Array index is out-of-bounds.

ArrayStoreException Assignment to an array element of an incompatible type.

ClassCastException Invalid cast.

IllegalArgumentException Illegal argument used to invoke a method.

IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.

IllegalStateException Environment or application is in incorrect state.

IllegalThreadStateException Requested operation not compatible with current thread state.

IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.

NumberFormatException Invalid conversion of a string to a numeric format.

SecurityException Attempt to violate security.

StringIndexOutOfBounds Attempt to index outside the bounds of a string.

UnsupportedOperationException An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Description

ClassNotFoundException Class not found.

Attempt to clone an object that does not implement the Cloneable


CloneNotSupportedException
interface.

IllegalAccessException Access to a class is denied.

InstantiationException Attempt to create an object of an abstract class or interface.

InterruptedException One thread has been interrupted by another thread.

NoSuchFieldException A requested field does not exist.

NoSuchMethodException A requested method does not exist.


Explanations of common Java exceptions
java.lang
You are trying to use your computer to solve a mathematical
ArithmeticException problem that you cannot solve yourself. Read up on your
arithmetics and try again.

See IndexOutOfBoundsException. The difference is that this


ArrayIndexOutOfBoundsException
exception refers to more than one finger.

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 are a burgler that are running a Java program during a


IllegalAccessException burglery. Please finish stealing the computer, leave the premises
and try again.

IllegalArgumentException You have tried to protest against a previous exception.

IllegalMonitorStateException Please turn your computer screen back on.

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.

You have put your index finger in an unacceptable place.


IndexOutOfBoundsException
Reposition it and try again.

InstantiationException Not everything can happen instantly. Please be more patient.

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 are using outdated units of measurement, for example inches


NumberFormatException or pints. Convert to SI. There is a known bug that causes this
exception to be thrown if you are very short or tall.

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

Someone else has modified your Java code. You


ConcurrentModificationException
should probably change your password.

In order for Java to work, you must have a stack


EmptyStackException of Java books on your desk. Actually, one is
enough if it is really thick.

You are too poor to be using Java. Switch to a


MissingResourceException cheaper language (such as Whitespace,
Shakespeare, Cow, Spaghetti or C#).

There are only four elements (earth, water, air,


NoSuchElementException
fire). The Fifth Element is just a movie.

You are bugged by too many secret


TooManyListenersException
organizations. Expect a SecurityException soon.

java.awt

You are using AWT, which means your GUI will be


AWTException ugly. This exception is only a warning and can be
ignored.

FontFormatException Your layout is ugly, or you have selected a bad


font, or too many fonts. Please consult a
professional designer.

Java thinks you are too stupid to be a


HeadlessException
programmer.

One of your hardware components (e.g.


IllegalComponentStateException harddrive, CPU, RAM) is broken. Please contact
your hardware vendor.

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.

Your personal profile contains suspicious information. If you


ProfileDataException are not a communist, terrorist, atheist etc., please contact the
CIA to correct the mistake.

java.awt.datatransfer

You are a bad mime. Noone can understand what you


are trying to express. Try something simpler, like
MimeTypeParseException
walking-against-the-wind och being-trapped-in-an-
invisible-box.

You are trying to use a flavor that is unknown to Java.


UnsupportedFlavorException Most people seem to get by using only vanilla and
cherry.
java.beans

You are too introverted. Be more extroverted. Stop being


IntrospectionException
such a nerd and go out and meet some people!

One of your properties has been vetoed. The message


PropertyVetoException should inform you of who did it and why. If it does not, you
probably shouldn't ask.

java.io

You have been trying to incinerate something


CharConversionException noncombustible. It is also possible that you have
tried turning yourself into a fish, but that's rare.

You get this exception because you don't know


EOFException what EOF stands for. Well, I'm not going to tell you,
Mr Ignoramus.

A carpenter should always know where his tools


FileNotFoundException
are.

You have been using IO despite of an


InterruptedIOException earlier IOException and your activities have been
interrupted.

InvalidClassException See ClassNotFoundException.

InvalidObjectException Objection overruled, as they say in court.

IOException IO stands for input/output and has to do with


sending and recieving data. IO is a security
problem and should not be used.

This can mean two things. Either something is


inactive and needs to be active, or something is
NotActiveException
active and needs to be inactive. Activate and
inactivate things randomly until things work.

You are trying to make a TV series based on a


NotSerializableException
movie.

You have issued a stream of objections. Please


limit yourself to one at a time and wait for the
ObjectStreamException
judge to make a ruling before issuing a new one.
See InvalidObjectException.

You seem to think that some optional data is


OptionalDataException
required. Don't make things harder than they are.

Your data stream is corrupted, which means that it


StreamCorruptedException has been stealing packages and selling them on the
black market.

You have tried to synchronize your failures with


someone else and you have turned out to be a
SyncFailedException
bigger failure that that person. Try to find someone
on your own level.

If you want to send something coded over the


network, you have to file your encryption key with
the NSA. If you don't, you will be regarded as a
UnsupportedEncodingException
terrorist and dealt with in the appropriate way. If
you get this exception, you should run away very
fast indeed.
UTF stands for Universal Transmission Format and
is a way of transmitting data that works regardless
UTFDataFormatException
of which format you use. You have tried to
transmit data over UTF using the wrong format.

You need to write the word "aborted" somewhere


WriteAbortedException in your program. It usually doesn't matter where,
you just have to do it.

java.net

BindException Java programming and bondage don't mix.

You are trying to connect something to something it


cannot be connected to. Try to connect it to something
ConnectException else. Perhaps it is possible to connect your things to
eachother via a special connection object that connects
to both ends of your desired connection.

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").

There is no route to the host. Contact the Road


NoRouteToHostException
Administration.

Ports and harbors must be placed right next to a water


PortUnreachableException
body. If placed inland, they will be unreachable.

This is the result of a serious breach of etiquette (such as


ProtocolException pukíng on your host). The solution is simple: Don't do
that!
You have connected your computer to a power outlet of
the wrong kind. Most of the times you have to find
SocketException
another outlet, but some computers have a switch on
the back where you can set the power outlet type.

You have connected your computer a power outlet with


SocketTimeoutException a timer and the time has run out. Such outlets should
only be used for flat-irons and similar things.

UnknownHostException Didn't your parents teach you to not talk to strangers?

You are trying to access an unknown service. The most


UnknownServiceException
known unknown service is perhaps Secret Service.

The sentence "You are I" is not syntactically correct.


URISyntaxException Change it to "You are me". What ever the hell that
means.

java.rmi

AccessException You are using Microsoft Access. Please don't.

Despite what is stated in the description of


java.net.BindException, RMI does support bondage.
AlreadyBoundException
However, you cannot tie up someone that is already
bound.

You are trying to connect something to something it


cannot be connected to. Try to connect it to something
ConnectException else. Perhaps it is possible to connect your things to
eachother via a special connection object that connects to
both ends of your desired connection.
You are trying to connect something that has to do with IO
to something it cannot be connected to. Try to connect it
ConnectIOException to something else. Perhaps it is possible to connect your
things to eachother via a special connection object that
connects to both ends of your desired connection.

Something is wrong with your marshal. What you should


do depends on what kind of marshal we are talking about.
It can be a field marshal, police, firefighter or just your
MarshalException
ordinary basic marshal. Note that this exception has
nothing to do with the Republic of the Marshall Islands,
a.k.a. RMI.

You are trying to use an object that does not exist. Create
NoSuchObjectException
it or don't use it, Einstein!

If you are using bondage, please make sure that at least


NotBoundException
one person is tied up.

This is a special exception that is thrown remotely. If


someone else's application has become so instable that it
RemoteException can't even produce an exception, then you may get the
exception instead. Please find the source and inform that
programmer of the error.

The Republic of the Marshall Islands has become instable.


If you live there, you should probably leave and don't
RMISecurityException
come back until your security can be guaranteed. If you
live elsewhere, you can ignore this exception.

ServerException Second serve. (Or double fault if applicable.)

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!

This exception should come as a total surprise to you. If it


UnexpectedException
did, everything is as it should be.

UnknownHostException Didn't your parents teach you to not talk to strangers?

You have not fullfilled your duties as an officer of the law


(or whatever marshal you used to work as). Note that the
UnmarshalException
correct term is "used to". You have been fired (which is
really ironic if you were a firefighter).

java.security

You have lost control of Microsoft Access. If


you cannot regain control or stop the
AccessControlException program in some other way, you should cut
the power to your computer as fast as
possible.

You should be careful with what you eat.


DigestException
Indigestion can be a serious problem.

Something somewhere appears to be unsafe.


If you have the power to do so, you should
GeneralSecurityException invade a random country (preferably in the
middle east). If you do not have such power,
you should at least get a gun.
You have explained your algorithm to a
disabled person in a way that is not suited to
InvalidAlgorithmParameterException
that person's level of understanding. Keep it
simple!

There are two rather different reasons for this


exception: 1. You are using the wrong key. My
advice is to paint small dots in different colors
on your keys to help you remember which
InvalidKeyException one is for which lock. 2. You are not allowed
to lock up disabled people without giving
them a key. If they are smart enough to figure
out how to use it, they have a right to move
freely.

You have used a disparaging term to describe


InvalidParameterException
a disabled person.

KeyException Do not try to unlock locks without a key.

You have lost your key. Most likely you left it


at the office (if you're trying to enter your
KeyManagementException
home) or at home (if you're trying to enter
the office).

The explanation for the


KeyStoreException previous KeyManagementException is that
there is a hole in your pocket.

You are trying to solve a problem in a


previously unknown way. Stop being so damn
NoSuchAlgorithmException creative and rewrite your program using old
algorithms. You can also patent your idea and
wait for it to be incorporated into a future
Java release.

If you are a single mom, you cannot be a


NoSuchProviderException housewife. First, you need to get a provider
for your family.

You have tried to take an action that you do


not have the privilege to take. For example,
getting away with murder is something that
only famous people can do, child molestation
PrivilegedActionException
is only for catholic priests and high ranking
jehova's witnesses, and only people with
managerial positions in private corporations
are allowed to steal money.

You are a woman and are trying to be the


provider of a family. Obviously, your husband
cannot be a housewife, so you need to let him
ProviderException
do the providing. Thinking that Java is old-
fashioned will not change reality. This is how
things work. Deal with it.

Either you have forged someone else's


signature, or your signature unacceptable. A
SignatureException
signature cannot be too ugly, too readable or
too large.

Damn. You dropped your key down a drain.


The only comfort I can offer is that the key
UnrecoverableKeyException should be unrecoverable for other people as
well, so it may not be necessary to change
your locks.
java.text

ParseException You are not making any sense. Calm down and try again.

try-catch method example

before:

public class MyException {


public static void main(String a[]){
for(int i=5;i>=0;i--){
System.out.println(10/i);
}
System.out.println("After for loop...");
}
}

after:

public class MyExceptionHandle {


public static void main(String a[]){
try{
for(int i=5;i>=0;i--){
System.out.println(10/i);
}
} catch(Exception ex){
System.out.println("Exception Message: "+ex.getMessage());
ex.printStackTrace();
}
System.out.println("After for loop...");
}
}

another example:

import java.util.Scanner;

class Division {
public static void main(String[] args) {

int a, b, result;

Scanner input = new Scanner(System.in);


System.out.println("Input two integers");

a = input.nextInt();
b = input.nextInt();
result = a / b;

System.out.println("Result = " + result);


}
}

class Division {
public static void main(String[] args) {

int a, b, result;

Scanner input = new Scanner(System.in);


System.out.println("Input two integers");

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.");
}
}
}

throws clause example :

public class MyThrowsClause {


public static void main(String a[]){
MyThrowsClause mytc = new MyThrowsClause();
try{
for(int i=0; i<5; i++){
mytc.getJunk();
System.out.println(i);
}
} catch (InterruptedException iex){
iex.printStackTrace();
}
}

public void getJunk() throws InterruptedException {


Thread.sleep(1000);
}
}
throw clause example:

public class MyExplicitThrow {


public static void main(String a[]){
try{
MyExplicitThrow met = new MyExplicitThrow();
System.out.println("length of JUNK is
"+met.getStringSize("JUNK"));
System.out.println("length of WRONG is
"+met.getStringSize("WRONG"));
System.out.println("length of null string is
"+met.getStringSize(null));
} catch (Exception ex){
System.out.println("Exception message: "+ex.getMessage());
}
}

public int getStringSize(String str) throws Exception


{
if(str == null){
throw new Exception("String input is null");
}
return str.length();
}
}

using finally block:

public class MyFinallyBlock {


public static void main(String[] a){
/**
* Exception will occur here, after catch block
* the contol will goto finally block.
*/
try{
int i = 10/0;
} catch(Exception ex){
System.out.println("Inside 1st catch Block");
} finally {
System.out.println("Inside 1st finally block");
}
/**
* In this case exception won't, after executing try block
* the contol will goto finally block.
*/
try{
int i = 10/10;
} catch(Exception ex){
System.out.println("Inside 2nd catch Block");
} finally {
System.out.println("Inside 2nd finally block");
}
}
}
user defined exception:

public class MyException extends Exception


{
public MyException(String mymsg)
{
super(mymsg);
}
}

public class ExceptionSample


{
public static void main(String args[]) throws Exception
{
ExceptionSample es = new ExceptionSample();
es.displayMymsg();
}
public void displayMymsg() throws MyException
{
for(int j=8;j>0;j--)
{
System.out.println("j= "+j);
if(j==7)
{
throw new MyException("This is my own Custom Message");
}
}
}
}
nested try block:

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);
}
}
}

When child class method is throwing border checked exception compared to


the same method of base class
import java.io.*;
class Building {
void color() throws IOException
{
System.out.println("Blue");
}
}
class Room extends Building{
void color() throws Exception
{
System.out.println("White");
}
public static void main(String args[]){
Building obj = new Room();
try{
obj.color();
}catch(Exception e){
System.out.println(e);
}
}
}
How to throw your own exception explicitly using throw keyword

class MyOwnException extends Exception {


public MyOwnException(String msg){
super(msg);
}
}

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();
}
}
}

How to throw an already defined exception using throw keyword


class Exception2{
static int sum(int num1, int num2){
if (num1 == 0)
throw new ArithmeticException("First parameter is not valid");
else
System.out.println("Both parameters are correct!!");
return num1+num2;
}
public static void main(String args[]){
int res=sum(0,12);
System.out.println(res);
System.out.println("Continue Next statements");
}
}
Arithmetic exception
Class: Java.lang.ArithmeticException
This is a built-in-class present in java.lang package. This exception occurs when an integer
is divided by zero.
class ExceptionDemo1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result = " +output);
}
catch(ArithmeticException e){
System.out.println ("Arithmetic Exception: You can't divide an
integer by 0");
}
}
}

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 Normal program execution is immediately branched when an exception is thrown.

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.