JAVA

Exception handling in java with examples

java-exception-handling
java-exception-handling

Exception Handling In Java

Exception handling is the programming instructions are defined in predefine syntax that compiles and check at compilation time. The Java programming return compile-time error due to poor understanding of the programmer. The error also generates at program execution time due to user or value or any interruption. The run-time error identified as an exception. Java programming provides built-in classes, keywords for handling the exceptions which generate at the time of program execution.

Exceptoion type in java
Exceptoion type in java

Keywords and Classes in Java Exceptions Handling

  1. throws():- It is a keyword that allows catching the exception for a particular instruction. In this, we define class name on the base of exception.
  2. try:- It is a keyword that allows defining the set of instruction that may generate an exception. It is basically used to define the block of statement.
  3. catch():- This keyword allows catching the error from try which generates at execution time. It uses after the try block.
  4. IOException:- It is a class that catches the input and output exception.
  5. Arithmetic Exceptions:- It is a class that allows managing the arithmetic related exception like divide by zero.
Types of exception in java
Types of exception in java
Example:-
import java.util.*;
Class A
{
   public static void main (String s[])
   {
      Scanner sc = new Scanner (System.in);
      System.out.print ("enter value");
       int x = sc.nextInt();
       System.out.print ("enter value");
        int y = sc.nextInt();
        try
         {
             int c = x/y;
              System.out.print ("sum is" + c);
               }
            catch (ArithmeticException e)
             {
                 System.out.print ("can't divide by zero");
                  }
          }
}

Also Read:- Java File Handling

ArrayIndexOutOfBound Exceptions

This exception class that allows managing the array index related exception. It catches those type of exception which related to an array size.

 

Example:-
import java.util.*;
Class A
{
   public static void main (String s[])
   {
      int b = 25;
      Scanner sc = new Scanner (System.in);
      int a[] = new int[20];
      for (int i=0; i<5; i++)
      {
          System.out.print ("enter value");
           a[i] = sc.nextInt();
             }
        try
        {
           System.out.print ("the value is" + a[b]);
            }
       catch (ArrayIndexOutOfBoundException e)
       {
          System.out.print ("can't use out of index");
            }
    }
}

Also Read:- Java Function

FileNotFound Exceptions

It is a class that allows checking the given file is available or not and manage its related exception.

Interrupted Exception

It is a class that allows managing the internal exception.

About the author

Udit Mutreja

Add Comment

Click here to post a comment