Anda di halaman 1dari 24

MANAGING ERRORS

AND EXCEPTION

By

Prof.Manikandan

QMC College, Medavakkam.


manisankar27@gmail.com

ERRORS
An errors may produce an incorrect output or
may terminate the execution of the program.
Types of Errors:
1. Compile time errors
2. Run time errors

1.Compile time errors


All the syntax errors will be detected and
displayed by the java compiler and therefore these
errors are known as compile time errors.

The most common Compile time errors:


Missing semicolons
Mismatch brackets
Missing double quotes in string and etc..
2.Run time errors:
A program may compile successfully creating the
.class file but may not run properly.
The most common Run time errors:
Dividing an integer by zero.
Converting invalid string to a number.
Negative size for an array.

EXCEPTION HANDLING
The exception handling is one of the powerful
mechanism provided in java.
It provides the mechanism to handle the runtime
errors so that normal flow of the application can
be maintained.

Exception:
Dictionary Meaning: Exception is an abnormal
condition.
In java, exception is an event that disrupts the
normal flow of the program.
It is an object which is thrown at runtime.

HIERARCHY OF EXCEPTION CLASSES

TYPES OF EXCEPTION

1.
2.

There are mainly two types of exceptions:


Checked Exception
Unchecked Exception

Checked Exception
The
classes
that
extend
Throwable
class
except
RuntimeException and Error are known as checked exceptions
e.g. IOException, SQLException etc.

Checked exceptions are checked at compile-time.

Unchecked Exception

The classes that extend RuntimeException are known as


unchecked exceptions .

e.g.ArithmeticException,NullPointerException,
ArrayIndexOutOfBoundsException etc.

Unchecked exceptions are not checked at compile-time rather they


are checked at runtime.

COMMON SCENARIOS OF EXCEPTION HANDLING

There are given some scenarios where unchecked


exceptions can occur.
They are as follows:

1. ArithmeticException occurs
If we divide any number by zero, there occurs an
ArithmeticException.
inta=50/0; //ArithmeticException

2. NullPointerException occurs

If we have null value in any variable, performing any


operation by the variable occurs an NullPointer
Exception.

Strings=null;
System.out.println(s.length());//NullPointerException

3. NumberFormatException occurs

The wrong formatting of any value, may occur


NumberFormatException.
Suppose I have a string variable that have characters,
converting this variable into digit will occur
NumberFormatException.

Strings="abc";
inti=Integer.parseInt(s);//NumberFormatException

4. ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it


would result ArrayIndexOutOfBoundsException as
shown below:

inta[]=newint[5];
a[10]=50;//ArrayIndexOutOfBoundsException

EXCEPTION HANDLING KEYWORDS

1.
2.
3.
4.
5.

Five keywords used in Exception handling:


try
catch
finally
throw
throws

TRY BLOCK

Enclose the code that might throw an exception in try block. It must
be used within the method and must be followed by either catch or
finally block.

Syntax of try with catch block


try{
...
}
catch(Exception_class_Namereference)
{
..
}
Syntax of try with finally block
try{
...
}finally{}

CATCH BLOCK

Catch block is used to handle the Exception. It must be used after the try block.

Example:
classSimple{
publicstaticvoidmain(Stringargs[])
{
try
{
intdata=50/0;

}
catch(ArithmeticExceptione)
{
System.out.println(e);
}

System.out.println("restofthecode...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero rest of the
code...

PROBLEM WITHOUT EXCEPTION HANDLING

classSimple{
publicstaticvoidmain(Stringargs[])
{
intdata=50/0;
System.out.println("restofthecode...");
}
}
Output:Exception in thread main
java.lang.ArithmeticException:/ by zero

WHAT HAPPENS BEHIND THE CODE

MULTIPLE CATCH BLOCK:


If

you have to perform different tasks at the occurrence of different Exceptions, use multiple catch block.

classExcep4
{
publicstaticvoidmain(Stringargs[])
{
Try
{
inta[]=newint[5];a[5]=30/0;
}
catch(ArithmeticExceptione)
{
System.out.println("task1iscompleted");
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println("task2completed");
}
catch(Exceptione)
{
System.out.println("commontaskcompleted");
}
System.out.println("restofthecode...");
}}
Output:task1 completed rest of the code...

FINALLY BLOCK

The finally block is a block that is always executed. It


is mainly used to perform some important tasks such
as closing connection.

classSimple
{
publicstaticvoidmain(Stringargs[])
{
try
{
intdata=25/0;
System.out.println(data);
}
catch(ArithmeticExceptione)
{
System.out.println(e);
}

finally
{
System.out.println("finallyblockisalwaysexecuted");
}

System.out.println("restofthecode...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero finally block is
always executed rest of the code...

THROW KEYWORD

The throw keyword is used to explicitly throw an


exception. We can throw either checked or
unchecked exception.

Example of throw keyword


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.

classExcep13
{
staticvoidvalidate(intage)
{
if(age<18)
thrownewArithmeticException("notvalid");
else
System.out.println("welcometovote");
}

publicstaticvoidmain(Stringargs[])
{
validate(13);
System.out.println("restofthecode...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:not
valid

THROWING OUR OWN


EXCEPTIONS
There may be times when we would like to throw
our own exceptions.
Exception is a subclass of Throwable and
therefore MyException is a subclass of Throwable
class.

import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z=(float)x/(float)y;
if(z<0.01)
{
throw new MyException("Number is too small");
}
}
catch (MyException e)
{
System.out.println("Caught my exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}
}
}

OUTPUT
Output: Caught my exception
Number is too small
I am always here