Exception handling in java

 Exception handling in java


Exception handling is a mechanism in Java that allows developers to handle errors and exceptions that occur during program execution. Here is an example of how to use exception handling in Java:


import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;


public class Main {

  public static void main(String[] args) {

    try {

      File file = new File("input.txt");

      Scanner scanner = new Scanner(file);


      while (scanner.hasNextLine()) {

        String line = scanner.nextLine();

        System.out.println(line);

      }


      scanner.close();

    } catch (FileNotFoundException e) {

      System.out.println("Error: file not found");

    }

  }

}

In this example, we try to read data from a file called input.txt. If the file is not found, the FileNotFoundException exception is thrown. We catch this exception and print an error message. If the file is found, we read each line of the file and print it to the console.


No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...