error related to exception handling in java - java

How to resolve this error? I have tried using throws to throw FileNotFoundException but still same error.
Compile-Time Error : "Default constructor cannot handle exception type Exception thrown by the implicit super constructor. Must define an explicit constructor "
CODE :
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileOne {
Scanner sc = new Scanner(System.in);
String file_name = sc.nextLine();
File obj = new File(file_name);
Scanner reader_obj = new Scanner(obj); // <--- error in this line
public static void main(String args[]) {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}
void create() {
try {
System.out.println("Enter a file name");
if (obj.createNewFile()) {
System.out.println("file name is" + obj.getName());
} else {
System.out.println("Already exists");
}
} catch (IOException e) {
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile() {
try {
FileWriter w = new FileWriter(obj);
w.write("Learning files now");
w.close();
} catch (IOException e) {
System.out.println("Exception occured while writing a file");
}
}
//method to read
/* use the Scanner class to read the contents of the text file created */
void readFile() {
while (reader_obj.hasNextLine()) {
String data = reader_obj.nextLine();
System.out.println(data);
}
reader_obj.close();
}
}

The line Scanner reader_obj=new Scanner(obj);, which is implicitly called by the default constructor, may throw a FileNotFoundException, which is a checked exception and must be handled.
One way of doing so is explicitly defining a no-arg constructor:
public FileOne() throws FileNotFoundException {
}
Although, if you're going to do that, you should consider moving the members' initialization in to it for clarity's sake.

Errors Resolved:
I used throws to throw exceptions in main() and reading() method.
Used FileReader class to read the data from the given input file
Final Code:
public class FileOne {
Scanner sc=new Scanner(System.in);
String file_name=sc.nextLine();
File obj=new File(file_name);
//method for creating a file
void create(){
try{
if(obj.createNewFile()){
System.out.println("file name is"+obj.getName());
}
else{
System.out.println("Already exists");
}
}
catch(IOException e){
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile(){
try{
FileWriter w=new FileWriter(obj);
w.write("Learning files now");
w.close();
}
catch(IOException e){
System.out.println("Exception occured while writing a file");
}
}
void reading() throws FileNotFoundException,IOException{
FileReader reader=new FileReader(file_name);
int i;
while((i=reader.read())!=-1){
System.out.print((char)i);
}
reader.close();
}
public static void main(String args[])throws FileNotFoundException,IOException{
FileOne f=new FileOne();
f.create();
f.writeFile();
f.reading();
}
}

Add the constructor as below :
public FileOne () throws FileNotFoundException {
}
Edit your void main () as below (You need to throw the exception from main as well) :
public static void main(String args[]) throws FileNotFoundException {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}

Related

How do I throw an exception and scan again if the input is not bigDecimal?

I want to scan bigDecimal but if the input scanned is not bigdecimal it should throw an custom exception and scan it again?
I am trying the below code but not able to reach conclusion.
Code:
import java.util.*;
import java.io.*;
class WrongInputException extends Exception{
WrongInputException(String s){
super(s);
}
}
public class Main
{
public static void main(String[] args) throws WrongInputException
{
try
{
int number;
Scanner sc = new Scanner(System.in);
while (!sc.hasNextBigDecimal())
{
throw new WrongInputException("Wrong data type of input.....");
}
number = sc.nextInt();
System.out.println(number);
} catch(NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
The problem is that you are not handling the Exception you throw
You should add a try catch block to handle it inside thw while an also add a sc.next(); to avoid the endless loop
while (!sc.hasNextBigDecimal())
{
try {
throw new WrongInputException("Wrong data type of input.....");
}catch (WrongInputException e) {
e.printStackTrace();
}finally {
sc.next();
}
}
Note that your try catch has no sence since you have your exception to throw
Sacnner#hasNextBigDecimal does not make sense while scanning input from the keyboard. It can be used while scanning values from a file or a Scanner on a String object.
You can do it as follows:
import java.math.BigDecimal;
import java.util.Scanner;
class WrongInputException extends Exception {
public WrongInputException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) throws WrongInputException {
BigDecimal number;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a BigDecimal: ");
try {
number = sc.nextBigDecimal();
System.out.println(number);
} catch (Exception e) {
throw new WrongInputException("Wrong data type of input.....");
}
}
}
A sample run:
Enter a BigDecimal: 1234
1234
Another sample run:
Enter a BigDecimal: xyz
Exception in thread "main" WrongInputException: Wrong data type of input.....
at Main.main(Main.java:19)
A demo of Scanner on a String object:
import java.math.BigDecimal;
import java.util.Scanner;
class WrongInputException extends Exception {
public WrongInputException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) throws WrongInputException {
BigDecimal number = null;
Scanner sc = new Scanner("123 987654321 12.34");
try {
while (sc.hasNextBigDecimal()) {
number = sc.nextBigDecimal();
System.out.println(number);
}
} catch (Exception e) {
throw new WrongInputException("Wrong data type of input.....");
}
}
}
Output:
123
987654321
12.34

Error:Exception in thread "main" java.lang.NullPointerException

The readfile class is a class i made so i can read some strings from file.txt and then print them in the console:
package mainpackage;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try {
x = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("Could not find file");
}
}
public void readFile(){
while(x.hasNext()){
System.out.print(x.nextLine()+"\n");
}
}
public void closeFile(){
x.close();
}
}
But when i call the methods of the class in the main i get an error like this:
Exception in thread "main" java.lang.NullPointerException. This is the call in main:
public static void main(String [] args)
{
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
Any ideas? thank you
You should not catch exception in openFile() or if catch it, throw new exception if you got exception in openFile() method Scanner will be null and in other method got null pointer exception.
package mainpackage;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile() throws Exception{
try {
x = new Scanner(new File("file.txt"));
} catch (Exception e) {
//in here throw (this/another) exception to caller or don't catch this exption
System.out.println("Could not find file");
throw new Exception("Could not find file");
}
}
public void readFile(){
while(x.hasNext()){
System.out.print(x.nextLine()+"\n");
}
}
public void closeFile(){
x.close();
}
}
And main driver for testing:
public static void main(String [] args)
{
try {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
} catch (Exception e) {
e.printStackTrace();
System.out.println("got exception");
}
}
If exception is thrown, what value is under "x"?
What happend next?
(You should use debugger to check readFile() func)
I need to clarify: Questions were asked to make #Marios P sit up and think.

error: exception java.io.FileNotFoundException

Can anyone tell me why I have this error: exception java.io.FileNotFoundException is never thrown in body of corresponding try statement.
I try to save text from a file in an ArrayList.
import java.io.*;
import java.util.*;
public class EditMembership
{
public static void main(String[] args) throws java.io.FileNotFoundException
{
ArrayList<String> member = readFromFile("database.txt");
System.out.println(Arrays.toString(member.toArray()));
}
public static ArrayList readFromFile(String fileName) throws java.io.FileNotFoundException
{
Scanner x = new Scanner(new File(fileName));
ArrayList<String> memberList = new ArrayList<String>();
try {
while (x.hasNextLine())
{
memberList.add(x.nextLine());
}
x.close();
}
catch(FileNotFoundException e)//here is the error
{
e.printStackTrace();
}
return memberList;
}
}
Because you aren't doing anything to open a file within the try block it's impossible to throw a File Not Found. Move the Scanner declaration down within the try block and I would expect that'll fix it. At that point you can remove the "throws" declaration from your method signature.

File Reading Error: NoSuchElementException with Scanner

I am relatively new to Java programming. Recently I decided to create a random system that stores, writes, and reads information on request. When reading a file I have already written with the program, I get the following errors:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ReadFile.readFile(ReadFile.java:24)
at User.main(User.java:35)
I'm assuming this errors are a result of the User class calling on the ReadFile class, because the rest of the program works fine so far.
The User class that pertains:
import java.io.*;
import java.util.*;
public class User
{
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
Scanner user_input = new Scanner(System.in);
String input;
System.out.println("User Information System:");
System.out.println("Please type the full name of the person you wish to lookup.");
input = user_input.nextLine();
System.out.println("UIS currently has the following data on " + input + ":");
if(input.equals("First Last"))
{
System.out.println("Opening Data on " + input + "...");
}
else
{
System.out.println("No Data found.");
}
if(input.equals("/create"))
{
CreateFile create = new CreateFile();
create.openFile();
create.addRecords();
create.closeFile();
}
if(input.equals("/read"))
{
ReadFile read = new ReadFile();
read.openFile();
read.readFile();
read.closeFile();
}
}
}
As well as the ReadFile class:
import java.io.*;
import java.util.*;
public class ReadFile
{
static Scanner scanner;
public void openFile()
{
try
{
scanner = new Scanner(new File("TestFile.txt"));
}
catch(Exception e)
{
System.out.println("Error reading file.");
}
}
public void readFile()
{
while(scanner.hasNext()) //Find a way to shorten this to a loop of printing whatever is in the file.
{
String a = scanner.nextLine();
String b = scanner.next();
String c = scanner.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
scanner.close();
}
}

JAVA Scanner object inside my constructor, cannot call it in my method

I am required to pass a file object to my constructor, and I am required to make a constructor in my method.
I am very confused as to why my code does not compile. It gives me several errors, and i am still struggling with the first one: sc cannot be resolved.
This is my class:
public class Reverser {
public Reverser(File file) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(file);
}
public void reverseLines(File outpr) {
PrintWriter pw = new PrintWriter(outpr);
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
new ArrayList < String > (Arrays.asList(words));
Collections.reverse(wordsarraylist);
if (wordsarraylist != null) {
String listString = wordsarraylist.toString;
listString = listString.subString(1, listString.length() - 1);
}
}
pw.write(listString);
}
}
and this is my main:
import java.util.*;
import java.io.*;
public class ReverserMain {
public static void main(String[] args) throws FileNotFoundException, IOException {
Reverser r = new Reverser(new File("test.txt"));
}
}
Are you adding more functions to this class? You can keep it simple with an approach like this:
public static void reverseLines(File inputFile, File outPutFile) {
try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outPutFile)) {
while (sc.hasNextLine()) {
// your logic goes in here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can use try-catch block with resources, will auto close the streams.
And when you are writing to the output file,if the file is already existing, do you want to append data or erase the contents of the file and write to a completely new file??
if you must use constructors:
public class Reverser {
File inputFile;
File outputFile;
public Reverser(File inputFile, File outputFile) {
this.inputFile = inputFile;
this.outputFile = outputFile;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void reverseLines() {
try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outputFile)) {
while (sc.hasNextLine()) {
// your logic goes in here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Declare sc outside of the constructor :
Scanner sc = null ;
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}

Categories