Exceptions:-
An exception is a problem that arises during the execution
of a program. An exception can occur for many different reasons.
Exceptions divided into 3
categories:-
1. Checked Exceptions
(Compile time Exception):-
These are Exceptions occurs when the program has wrong syntax
or the grammar of the language. These exceptions can be identifying
during compilation time. Compiler identifies the checked exceptions. Desk checking mechanism is the solution of compile time
errors (checked exceptions).
2. Unchecked Exception (Runtime Exceptions):-
These Exceptions
are detected by JVM at the time of running the program. “Exception handling”
mechanism is solving these types of exceptions.
3. Errors:-
These errors represent bad logic. These errors are not
detected by the compiler or JVM. Logical errors are detected by comparing the
program output with manually calculated result.
Ø
An exception is an
error that can be handled. When there is an exception JVM displays exception
name & its description.
Ø
An error cannot be
handled.
Exception Handling Mechanism:-
1.
Try
block.
2.
Catch
block.
3.
Finally
block.
4.
Throws.
5.
Throw.
If we have
exception doubt in the program that can implement in try block.
If exception
is available it will throws corresponding catch
block.
There is an
exception catch and finally block is executed.
An exception
is not available catch will not execute and finally block is execute.
Finally block has closing connection.
We can use
more than one catch block.
Example:-
try{
Statement; //
implement code
}
catch(Exception
exobj) //exobj is object of an
exception, it has exception details.
{
out.println(exobj); //it display exception details
}
catch(Exception
ex)
{
out.println(ex); //it display exception details
}
finally
{
out.close(); //close connection
}
Example Program:-
public class Exceptionss {
public static void
main(String a[]){
int d=5,b=10,c;
try{
c=d/b;
if(d<10)
{
MyException me=new MyException("error");
throw
me;
}
}
catch(ArithmeticException ae)
{
ae.printStackTrace();
}
catch(MyException
me)
{
System.out.println(me);
}
}
}
class MyException extends Exception
{
String msg;
MyException()
{
}
MyException(String msg)
{
super(msg);
this.msg=msg;
}
}
No comments:
Post a Comment