Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses
Showing posts with label Exception Handling. Show all posts
Showing posts with label Exception Handling. Show all posts

How to use catch block to handle chained exceptions?

Program to demonstrate multiple catch blocks handling chained exceptions in Java

import java.io.IOException;


public class ChainedException {

   public static void main(String[] args) {

      int i = 10;
      try {
 i = i / 0;
 System.out.println("In First try block");
      }catch(ArithmeticException ae) {
 System.out.println("In First Catch Block");
 System.out.println("Arithmetic Exception Handled :\n" + ae);
 
        try {
    throw new IOException();
 }catch(IOException ioe) {
    System.out.println("In Second Catch Block");
    System.out.println("IOException Handled :\n" + ioe);
    try {
       throw new NumberFormatException();
    }catch(NumberFormatException nfe) {
       System.out.println("In Third Catch Block");
       System.out.println("NumberFormatException Handled  :\n" + nfe);
    }

  }

      }
   }
}



Output of the program : 




Program to demonstrate working of finally block in Java

Program to demonstrate working of finally block in Java

package com.hubberspot.examples;

public class FinallyBlock {

   public static int f(int i) {
 System.out.println("Inside method f()");
 try{
           System.out.println("Print 1");
    if(i == 1)
  return 1;
    System.out.println("Print 2");
    if(i == 2)
  return 2;
    System.out.println("Print 3");
    if(i == 3)
  return 3;
    System.out.println("Print 4");
    if(i == 4)
  return 4;
  }finally{
      System.out.println("Always returns below value");
      return 5;
   }
 }
 
   public static void main(String[] args) {
  
       for(int i = 1; i < 5; i++)
       {
   System.out.println(f(i));   
       }

   }

}


Output of the program : 


 

A simple Java program demonstrating methods of Exception class

A simple Java program demonstrating methods of Exception class

public class ExceptionMethodsDemo {

  public static void first() {
    try {
    System.out.println("In try block : ");
    throw new Exception("New Exception");
    }
    catch(Exception e) {
    System.out.println("In catch block : ");
    
    System.out.println("getMessage() : " 
        + e.getMessage());
    
    System.out.println("getLocalizedMessage() : " 
        + e.getLocalizedMessage());
    
    System.out.println("toString() : " 
        + e.toString());
    
    System.out.println("getClass().getName() : " 
        + e.getClass().getName());
    
    System.out.println("getCause() : " 
        + e.getCause());
    
    int i = 1;
    
    for(StackTraceElement ste : e.getStackTrace()) {      
    
      System.out.println("e.getStackTrace() : method "
         + i +" "+ ste.getMethodName());      
      i++;
    }
    
    System.out.println("printStackTrace() : ");
    e.printStackTrace(System.out);
    
    }
  }

  public static void second() {
  first();
  }

  public static void third() {
  second();
  }

  public static void main(String[] args) {
    third();
  }

}




Output of the program :




Creating a User Defined Exception class with Constructor having String argument in Java

Program to create a User Defined Exception class with Constructor having String argument in Java

class UserException extends Exception {

   public UserException() {
  
   }
 
   UserException(String s){
 super(s);
   }
}

public class ExceptionTest {
 
   public void method1() throws UserException{
  
    System.out.println("Throwing UserException from method1()");
 throw new UserException();
  
   }
 
   public void method2() throws UserException{
    
 System.out.println();
 System.out.println("Throwing UserException from method2()");
 throw new UserException("Exception thrown from method()2");
 
   }
    
   public static void main(String[] args) {
  
 ExceptionTest test = new ExceptionTest();

 try{
           test.method1();
 }catch(UserException e){
    e.printStackTrace(System.out);
 }
  
 try{
    test.method2();
 }catch(UserException e){
    e.printStackTrace(System.out);
 }

   }

}




Output of the program :






Video tutorial to demonstrate how to create user-defined or application specific exceptions in Java.








EOFException : Program to detect end of file in Java

Program to demonstrate EOFException and a way to detect end of file in Java.

package com.hubberspot.exception.example;

import java.io.*;

public class EndOfFileDetection { 
  public static void main(String[] args) {
    try {
      DataOutputStream output = new DataOutputStream
        (new FileOutputStream("C://EndOfFile.dat"));
      output.writeChars("Welcome ") ;
      output.writeChars("to ") ;
      output.writeChars("Hubberspot !.") ;
      output.close();
      
      DataInputStream input = new DataInputStream
        (new FileInputStream("C://EndOfFile.dat"));
      while (true) {
        System.out.print(input.readChar());
      }
    }
    catch (EOFException ex) {
      System.out.println("");
      System.out.println("All data read");
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}


Output of the program :



How to Create User Defined Exceptions in Java ?.

In this section of blog, we will be looking into more depth about Exception handling. In this section we will see how to create user defined exceptions in Java ?. The Java API provides several Exception classes which are adequate for most purposes. However, in some cases, we may encounter a situation which cannot be described by standard exception types. For example, suppose we are accepting the birthdate of the user. If the user enters month as 15, we may want to treat it as an InvalidMonthException. For such cases, we may need to define our own exception types.

A user defined exception class must extend Exception. The syntax is given below:

Syntax: 

class UserDefinedException extends Exception
{
  // code
}

To give a default text message regarding the exception, simply override the toString() method. This class can also define a constructor which can pass this string to the superclass constructor.

Program to demonstrate User Defined Exceptions 

package com.hubberspot.exception.example;

class InvalidMonthException extends Exception
{
  public String toString()
  {
    return "Invalid Month given";
  }
}
class InvalidDayException extends Exception
{
  public String toString()
  {
    return "Invalid Date given";
  }
}
class UserExceptionDemo
{
  public static void main(String[] args)
  {
    try
    {
     if(args.length < 3)
       throw new NullPointerException();
     else
     {
       int dd = Integer.parseInt(args[0]);
       int mm = Integer.parseInt(args[1]);
       int yy = Integer.parseInt(args[2]);
       if(dd < 1 || dd > 31)
          throw new InvalidDayException();
       if(mm < 1 || mm > 12)
                throw new InvalidMonthException();
                  System.out.println("Valid Input");
     }
   }
   catch(Exception e)
        {
System.out.println(e);
}
 }
}

Output 1: java UserExceptionDemo 
 java.lang.NullPointerException

Output 2: java UserExceptionDemo 24 6 2011
 Valid Input

Output 3: java UserExceptionDemo 24 16 2012
 Invalid Month given

Output 4: java UserExceptionDemo 31 2 2012
 Invalid Date is given





Video tutorial to demonstrate how to create user-defined or application specific exceptions in Java.











Exception Handling in Java : Checked and Unchecked Exceptions

Introduction
Errors and unexpected situations are an integral part of programming. It rarely happens that programs are error free. It is the responsibility of the programmer to identify all possible errors and correct them so that the program runs. There are different types pf errors that can occur in a program. Syntax errors occur when the rules and the syntax of the language is not followed. For e.g. if we forget to end a statement with semicolon or we misspell a keyword. Syntax errors are detected and reported by the compiler. Logical errors occur when we make a mistake in the program logic i.e,. algorithm. For e.g. instead of addition, we perform subtraction. In such a case, the program will run but will not give the correct output. Removal of logical errors is called debugging which should be done by the programmer.
Another kind of errors are called exceptions which are run-time errors which occur when the program is running. Now here we will look after exceptions and exception handling in detail.

Dealing with Errors
Since errors are an intrinsic part of programming, we cannot ignore them but we have to deal with errors. When a runtime error occurs in a program, there are two things that should ideally take place.
  1. The program should return to a stable state and allow the user to take further action.
  2. If the program has to be terminated, it should five the user to save all work before termination.
The above may not happen automatically in the program. For this purpose, the programmer must understand the various causes of errors, anticipate what kind of errors can occur in the program so that the program does not terminate abnormally when some error occurs.

Causes of errors :
  1. User Input Error – These errors occur in input values given to a program. These include invalid out of range values given to variables, values of wrong types, invalid paths etc.
  2. Device Error – These errors are related to the hardware devices which the program uses. For e.g., a network connection may be unavailable, the printer may fail, the removable disk may be malfunction while file I/O etc.
  3. Physical Limitations – These errors are caused due to limitations on available the printer, stack space for recursion , limited connection bandwidth etc.
  4. Code Errors – These errors are caused due to the code itself. These include violation of constraints, invalid method calls, illegal assignments, undefined class, exceeding array limits etc.
Any of these can occur in a program. An elegant way to handling these occurences is by theuse of an Exception handling mechanism which is discussed in the next section.

Exceptions:
An exception is an abnormal condition that arises in a code at run time. In other words an exception is a runtime error. Java has an inbuilt exception handling mechanism.
An exception in Java is an object trhat describes the occurrence of some exceptional or unexpected condition during execution. It encapsulates the information of the error so that further action can be taken. This is what happens when an exception occurs:
  1. When an exception arises, an object representing that exception is exception itself.
  2. The method in which the error occurred may choose to handle the exception itself.
  3. If the method can’t handle the exception, it throws this exception object to the method which called it.
  4. The exception is caught and processed by some method or finally by the default java exception handler.
Exception Classes
There are several predefined execution classes defined in the java.lang package . In the java programming language, an exception object is always an instance of a class derived from Throwable.
All exception classes extend Throwable. From the Throwable class, there are two separate hierarchies: Error and Exception.

Error: These classes are related to internal errors and resources exhaustion during runtime. The user has to control over such situations and hence, these types cannot be handled by the program. The java runtime system takes default action when this type of situation occurs.

Exception: The classes belonging to this hierarchyrepresents exceptions that a program would want to be made aware of during execution. There are two brancheshere: exceptions of the type RuntimeException and those that do not inherit from RuntimeExc eption. RuntimeException represents many common programming errors that occur runtime.

Checked and UncheckedExceptions
Exceptions can be classified into 2 types : Checked and Unchecked.

Checked Exceptions: Except for RuntimeException, Error, and their subclasses, all other exceptions are called checked exceptions. It means that it is compulsary for the user to check i.e, to handle an exception. If a method throws a checked exception then the method must take the responsibilty to deal with it. The method must either catch the exception and take appropriate action, or pass the execution on to its caller.
Examples : IOException, ClassNotFoundException, InterruptedException, CloneNotSupportException

Unchecked Exception: Exception defined by Error and RuntimeException classes and their subclasses are known as unchecked exceptions. It means that it is not mandatory for a method to deal with such kinds of exceptions, The compiler doesn’t check if a method handles or throws this exception. Such exceptions are either irrecoverable and the program should not attempt to deal with them or they cannot be treatedas exceptions.
Examples- NullPointerException, ArrayIndexOutofBoundsException,
ArithematicException, NumberFormatException etc

 
© 2021 Learn Java by Examples Template by Hubberspot