Ask coding questions

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

When I run, I get this error: error: unreported exception Exception; must be caught or declared to be thrown

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 class is set up:

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

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

    Scanner input = new Scanner(;

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

    PrintWriter outputFile = new PrintWriter(fileName);



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

EpicGamer007 (1736)

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