Skip to content

Latest commit

 

History

History
54 lines (22 loc) · 1.21 KB

Exception handling in java.md

File metadata and controls

54 lines (22 loc) · 1.21 KB

Exception handling in java

s

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");

}

}

}s

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.