Exceptional Example in Java using Try-Catch
When an error occurs in
a method, Java creates an object of the Exception method. On making an object
of exception method, java send it to the program by throwing the object of
exception method. The Exception Object states the information of type of error
and status of program during the exception Occurred.
Following are the
Keyword used in implementing Exceptional-Handling-
- Try
- Catch
- Throw
- Throws
- Finally
How to implement Try-Catch Block
The Try Block contain a
set of statements that raise an exception-event within the scope
of method. If the exception arises in Try-Block. the appropriate
handler with the Try Block proceed the exception.
As We Know, the Catch
Block is used as exceptional-handler. The Exception that arises in the try
block is handled by the Catch -Block. Each Try block preceded by one Catch
block. The catch block specifies the type of exception need to catch.
Let Us Understand With Example
class Exception
Unhandled
{
Public static void
main(String args[])
{
int num1=0;
int num2=8;
int num3=num2/num1;
System.out.println("The
num3 = " +num3);
}
|
The above code contain a
class Exception Unhandled, Which on Compile gives us Arithmetical exception
with no exception being handled .In this code the Java run-time a exception
when a number is divided by zero. The output of the code shows that the exception
thrown is the object of the subclass of exceptional class.
Output in Command Prompt
C:\Documents and Settings\Administrator>cd\ C:\>cd new folder\ C:\New Folder>javac ExceptionUnhandled.java C:\New Folder>java ExceptionUnhandled Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionUnhandled.main(ExceptionUnhandled.java:7) |
See How we going to implement Try-Catch Block in
the above coding
Inorder to handle
exception ,you need to implement the Try-Catch. If an exception arises within a
try block, the appropriate exception handler associated with try block
handles the exception. The Catch block catches the object of the exception class
as a parameter. Once the exception is caught in catch-block, the expression
within the corresponding block is executed.
class
ArithmeticException
{
public static void
main(String args[])
{
int num1 = 0;
int num2=10;
int num3=0;
try
{
num3=num2/num1;
System.out.println("The
result =" +num3);
}
catch(ArithmeticException
e)
{
System.out.println("Division
by Zero is done");
}
}
}
|
Output in Command Prompt
C:\java>javac
ArithmeticExcep.java
C:\java>java
ArithmeticExcep
Division by Zero is done
0 comments:
Post a Comment