Exceptions Handling Fundamentals

Exceptions Handling Fundamentals

When there is an exception, the user data may be corrupted. This should be tackled by the programmer by carefully designing the program.

How do you handle exceptions?

Java exception handling is managed via five keywords: try, catch, throw, throws & finally

  • Try block: contains the program statements that you want to monitor for exceptions
  • Catch: you can catch an exception using this & handle it in some time manner
  • Throw: used to manually throw an error
  • Throws: Any exception that is thrown out of a method must be specified as such by a throws clause
  • Finally: Any code that absolutely must be executed after try block completes is put in a finally block

Try-Catch Mechanism

  • We write the block of statements which arises the exception at run time inside try block, the normal code logic is placed inside a block of code starting with the “try” keyword
  • We write the block of statements which will generates user friendly error messages inside catch block.
  • Finally block is optional.This block contains code that is ALWAYS executed, either after the “try” block code or after the “catch” block code
  • Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file)
  • Exception handling has 2 benefits: First, it allows you to fix the error and secondly, it prevents the program from automatically terminating.
Syntax of try-catch
try
{
//code that may throw exception
}
catch(Exception_class_Name ref)
{}
Syntax of try-finally
try
{
//code that may throw exception
}
finally
{}
Example
class test
{
public static void main(String args[])
{
int d, a; try
{
d = 0;
a = 50 / d;
System.out.println(“This will not be printed.”);
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero.”);
}
System.out.println(“After catch statement.”);
}
}

Output:
Division by zero.
After catch statement.

Leave a Reply

Your email address will not be published. Required fields are marked *