Ask coding questions

← Back to all posts
How to catch a thrown exception in my main class
VedKhandalkar (0)

When I run test2.java, I get this error:

Main.java:4: error: unreported exception Exception; must be caught or declared to be thrown
test2.main(null);
^

How do I set my main class to catch/declare to throw the exception? Do I have to do this for every class I call to be executed?

This is how my test2.java class is set up:

import java.lang.Math;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.*;

public class test2 {
  public static void main(String[] args) throws IOException {

    Scanner input = new Scanner(System.in);

    String fileName = "MyName.txt";
    String name = "Ved";

    PrintWriter outputFile = new PrintWriter(fileName);

    outputFile.println(name);

    outputFile.close();

    System.out.println("Name [" + name + "] written to file {" + 
fileName + "} succesfully.");



  }
}
Comments
hotnewtop
EpicGamer007 (1736)

because the main method in test2.java throws IOException, any method which uses that method much try {} catch(IOException) {} it or throws IOException itself. Basically, in Main.java, add throws IOException just like the method in test2.java