adsterra

5 important keywords in Java Exception Handling


5 important keywords related to Java Exception Handling:

1.try-block:

↪️The code which might raise exception must be enclosed within try-block.
↪️try-block must be followed by either catch-block or finally-block

2. catch block:

↪️It contains handling code for any exception raised from corresponding try-block and it must be enclosed within catch-block.
↪️catch-block takes one argument which should be of type Throwable or one of its sub-classes i.e.; class-name followed by a variable.
↪️This variable contains exception information for exception raised from try-block.

3.finally-block:

↪️finally block is used to perform clean-up activities or code clean-up like closing database connection & closing streams or file resources, etc.
↪️finally block is always associated with try-catch block.

Code:
class Finally1 {
  public static void main(String[] args) {

    try {
      int data= 25/0;
    }
    catch (ArithmeticException e) {
      System.out.println(e);
    }

    finally {
      System.out.println("finally block will execute always.");
    }
  }

}
Result:


4.throw clause:

↪️Sometimes, programmer can also throw/raise exception explicitly at runtime on the basis of some business condition.
↪️To raise such exception explicitly during program execution, we need to use throw keyword.

Code:
class Throw1
{
static void Check(int age,int marks)
{
if(age<12&&marks<40)
{
throw new ArithmeticException("Student is not Eligible");
}
else
{
System.out.println("Student Entry id Valid");
}
}
public static void main(String[] args)
{
System.out.println("Welcome to ");
Check(15,49);
System.out.println("Have a Nice Day");
}
}
Result:


5.throws  clause:

↪️throws keyword is used to declare the exception that might raise during program execution.
↪️Any number of exceptions can be specified using throws clause, but they are all need to be separated by commas (,).
↪️throws clause is applicable for methods & constructor but strictly not applicable to classes.




Post a Comment

0 Comments