05 August 2023

Exception Handling In Java - learngreen.net

 

Exception Handling In Java

  An exception in Java is an occurrence that modifies the usual course of a program's execution. It happens when something unforeseen or incorrect happens while a program is running, such as division by zero, accessing an array index that is outside its bounds, or attempting to open a file that doesn't exist. If an exception is not handled correctly when it occurs, the program stops unexpectedly.

Java's exception-handling framework offers a reliable and potent mechanism for handling exceptions.

Throwable class hierarchy:- Classes that derive from the Throwable class are used to represent all exceptions in Java. Exception and Error are Throwable's two primary subtypes. Checked exceptions and unchecked exceptions are additional categories for exceptions. Unchecked exceptions do not require explicit handling, but checked exceptions must be explicitly handled or specified in the method signature.

Try-catch blocks are used to enclose code that might raise an exception in try-catch blocks. If an exception arises inside the try block, the appropriate catch block handles it. To handle various error kinds, multiple catch blocks can be utilized. When the thrown exception matches the provided exception type, the catch block is put into action.

When throwing an exception, the throw keyword is used explicitly. It is frequently used inside of methods to signify that a specific circumstance has happened and the software needs to handle it. An instance of the exception class being thrown is then given as the result of the throw command.


Finally block:- The try-catch block is followed by the optional finally block. It is employed to make sure that specific code is executed whether or not an exception arises. Even if an exception is caught and dealt with in a catch block, the code contained in the final block is still carried out. Finally, blocks are frequently used to release resources by severing network connections or files.





  package Java;
 import java.rmi.AccessException;
 public class EH {
 /* Method to perform division and
  * throw an ArithmeticException if divisor is zero	 
  */
 public static int divide(int dividend,int divisor) {
 if (divisor==0) {
/* Throwing an ArithmeticException
 *  with a custom error message	 
 */
 throw new ArithmeticException
 ("Division by zero not allowed."); 
 }
// Performing the division and returning the result
 return dividend / divisor;
 }
 public static void main(String[] args) {
 try {
// Calling the divide method with 2 and 0 as arguments	 
 int result = divide(2,0);
 System.out.println("Result: "+result);
  } catch (ArithmeticException e) {
 /* Catching the ArithmeticException
  * if division by zero occurs	  
  */
 System.out.println("can not divide by zero");	  
  } finally { 
 /* The code in the finally block will
  * always be executed, regardless of
  * whether an exception occurs or not.	  
  */
 System.out.println("executed");
 //Output-> can not divide by zero
 //         executed
      
	 }
   }
 }

 Java additionally offers additional exception types that are a part of the standard Java API or often used in Java programming, in addition to checked and unchecked exceptions, The checked exception IOException stands for a general I/O (input/output) issue. When reading from or writing to files, streams, or during other I/O operations, it is thrown.


 package Java;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 
 public class IOE {
 public static void main(String[] args) {
 // Try block to handle the code that may throw exceptions	 
 try {
 /* Creating a FileInputStream to
  * read from the file "Documents File"	 
  */
 FileInputStream file = new FileInputStream("Documents File");
 //Reading a single byte of data from the file
 int data = file.read();
//Displaying the data read from the file
 System.out.println("Data: " + data);
 // Closing the FileInputStream after use
 file.close();
  }
 /* Catching the FileNotFoundException
  * if the file "Documents File" is not found
  */
 catch (FileNotFoundException e) {
 System.out.println("Error: File not found.");
 /* Catching the IOException
  * that may occur while reading the file
  */
 } catch (IOException e) {
 System.out.println("Error: Unable to read the file.");
	 }
   }
 }

 When a program tries to access or perform operations on an object reference that is null (not pointing to any object), it throws the unchecked exception known as a NullPointerException. This error will be thrown if you attempt to call methods or access fields on a null object reference.



 package Java;
 public class NPE {
 public static void main(String[] args) {
 /* Creating a String reference named
  * "word" and initializing it to null 
  */
 String word = null;
 /* Try block to handle the code
  * that may throw exceptions
  */
 try {
 /* Attempting to get the length of
  * the string, which will throw
  * NullPointerException 
  */
 int length = word.length();
 System.out.println
 ("Length of the string: " + length);
 // Catching the NullPointerException
 // if the "word" reference is null
     } catch (NullPointerException e) {
 System.out.println("Error: The string is null.");
  //Output-> Error: The string is null.
   }	 
  }
 }

 NumberFormatException: This unchecked exception happens when a string that is not a valid number is attempted to be converted to a numeric type (such as an int or double) using a method like Integer.parseInt( ) or Double.parseDouble( ).



 package Java;
 public class NFE {
 public static void main(String[] args) {
 /* Creating a String named "sentence"
  * containing a sentence */	 
 String senetnce = "Lets Play";
 /* Try block to handle the code
  * that may throw exceptions */
 try {
 /* Attempting to parse the
  * "sentence" string into an int */	 
 int number = Integer.parseInt(senetnce);
 System.out.println("Parsed number: "+number);
 /* Catching the NumberFormatException
  * if the parsing fails */
 } catch(NumberFormatException e) {
 System.out.println("Invalid number format");
 // Output-> Invalid number format
     }
   }
 }

 Casting an object into a type it is incompatible with results in the unchecked exception known as a "ClassCastException." This frequently occurs when casting objects that are not inherited from one another from distinct class hierarchies.



 package Java;
 public class CCE {
 public static void main(String[] args) {
 /* Creating an Object reference
  * named "obj" and assigning
  * it a String object */	 
 Object obj = "Welcome";
 /* Try block to handle
  * the code that may
  * throw exceptions */
 try {
 //Trying to cast a String to Integer
 Integer num = (Integer) obj;	
 System.out.println(num);
 /* Catching the ClassCastException
  * if the cast fails */
 } catch(ClassCastException e) {
 System.out.println("Unable to cast");	 
 //Output-> Unable to cast
	 }
    }
  }

 IllegalArgumentException:- When an illegal or improper argument is supplied to a method, this unchecked exception is raised. This exception might occur, for instance, if a negative value is passed to a method that expects positive values.



 package Java;
 import java.util.Scanner;
 public class IAE {
 public static void main(String[] args) {
 /* Create a Scanner object to
  * read input from the console	 
  */
 Scanner scanner = new Scanner(System.in);
 try {
 // Prompt the user to enter a number	 
 System.out.println("Enter a number: ");
 // Read the input number from the user
 int number=scanner.nextInt();
/* Call the validateNumber method
 * to check if the number is valid
 */
 validatNumber(number);
 // Display a message if the number is valid
 System.out.println("valid number");
 } catch (IllegalArgumentException e) {
 /* Catch the IllegalArgumentException
  * if the number is invalid	 
  */
 System.out.println("Invalid number provided");	 
   }
 finally {
 // Close the scanner to release resources	
 scanner.close();	 
 }
  }
 /* Method to validate the number and
  * throw an IllegalArgumentException
  * if it is less than or equal to 10
  */
 public static void validatNumber(int number) {
 if (number <= 10) {
  /* Throwing an IllegalArgumentException
   * with a custom error message	 
   */
 throw new IllegalArgumentException
 ("Number must be greater than 10"); 
	 }
   }
   

 

 IndexOutOfBoundsException:- When accessing an incorrect index in arrays, lists, or other indexed data structures, this unchecked exception is raised. Both StringIndexOutOfBoundsException and ArrayIndexOutOfBoundsException are included.



 package Java;
 public class IOBE {
 public static void main(String[] args) {
 int[] digits = {8,5,98,56,};
 try {
 int element = digits[4];
//Accessing an invalid index
 System.out.println(element);
 } catch(IndexOutOfBoundsException e) {
 System.out.println("Index out of bounds");	 
     }
   }
 }
//Output-> Index out of bounds

 SecurityException:- This checked exception is thrown if a security breach occurs and shows that the program lacks the authorization to carry out specific tasks.

OutOfMemoryError:- When the Java Virtual Machine (JVM) runs out of memory, this error (not an exception) manifests itself. When there is not enough memory to allocate new objects, it occurs.

StackOverflowError:- This is an error (not an exception) that happens when a program's call stack becomes larger than it is designed to be. It frequently occurs when recursion is excessive or infinite.

These are only a few illustrations of the numerous Java exception kinds. Many other specialized exceptions for particular uses, such as database access errors, networking problems, and more, are defined by the standard Java API and third-party libraries. For the purpose of creating dependable and resilient Java applications, it is crucial to comprehend various exception kinds and how to handle them.

















No comments:

Post a Comment