1

I am getting the error as "unreported exception ioexception; must be kept or declared to be thrown". It is the error in the path provided or in try - catch block.

import java.io.*;
import java.util.regex.*;

class RegexMobileExtractor {

    public static void main(String[] args) {
        try {
            Pattern p = Pattern.compile("(0|9)?[7-9][0-9]{9}");
            PrintWriter pw = new PrintWriter("C:\\Users\\HP\\Desktop\\CODE\\JAVA_EX\\copy\\output.txt");
            BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\CODE\\JAVA_EX\\copy\\input.txt"));

            //PrintWriter pw = new PrintWriter("output.txt");
            //BufferedReader br = new BufferedReader(new FileReader("input.txt"));

            String line = br.readLine();
            while( line!= null) {
                Matcher m = p.matcher(line);
                while(m.find()) {
                    pw.println(m.group());
                }

                line = br.readLine();
            }

            pw.flush();
            pw.close();
            //br.close();
        } catch (FileNotFoundException obj) {
            System.out.println("errr occured");
        }
    }
}
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Programmer
  • 21
  • 3

2 Answers2

0

This line of code: br.readLine(); may throw IOException. This is chacked exception and compiler force you to process it, that's why you have to add additional catch block:

catch (IOException e) {
    e.printStackTrace();
}
Ibrokhim Kholmatov
  • 1,079
  • 2
  • 13
  • 16
0

Change the line

} catch (FileNotFoundException obj) {
    System.out.println("errr occured");
}

to

} catch (IOException obj) {
    System.out.println("errr occured");
}

Since IOException is a parent of FileNotFoundException class, you will handle both kinds of exception.

Also, consider using try-with-resources which would close your files automatically.

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416