Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8579893
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T20:42:32+00:00 2026-06-11T20:42:32+00:00

I was trying to understand why to use exceptions. Suppose if I have an

  • 0

I was trying to understand why to use exceptions.
Suppose if I have an program,

(without using try/catch)

public class ExceptionExample {

private static String str;

public static void main(String[] args) {
    System.out.println(str.length());
}

I got exception

Exception in thread "main" java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:22)

Now using try/catch,

public class ExceptionExample {

private static String str;

public static void main(String[] args) {
    try {
        System.out.println(str.length());
    } catch(NullPointerException npe) {
        npe.printStackTrace();
    }
}

}

I got Exception,

java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:9)

Now my question is,

In both the cases I have got the same message printed. So what is the use of using try/catch? and

What can we do after catching exception, in this case I have printed the stack trace. Is catch used only for printing the trace or for finding exception details using getMessage() or getClass()?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T20:42:33+00:00Added an answer on June 11, 2026 at 8:42 pm

    The difference is pretty big, actually.

    Take the first one and add a line after the print:

    public class ExceptionExample {
    
        private static String str;
    
        public static void main(String[] args) {
            System.out.println(str.length());
            System.out.println("Does this execute?");
        }
    }
    

    You’ll see that Does this execute? isn’t printed because the exception interrupts the flow of the code and stops it when it isn’t caught.

    On the other hand:

    public class ExceptionExample {
    
        private static String str;
    
        public static void main(String[] args) {
            try {
                System.out.println(str.length());
            } catch(NullPointerException npe) {
                npe.printStackTrace();
            }
            System.out.println("Does this execute?");
        }
    }
    

    Will print both the stack trace and Does this execute?. That’s because catching the exception is like saying, “We’ll handle this here and continue executing.”

    One other remark, the catch block is where error recovery should happen, so if an error occurs but we can recover from it, we put the recovery code there.

    Edit:

    Here’s an example of some error recovery. Let’s say we have a non-existent file at C:\nonexistentfile.txt. We want to try and open it, and if we can’t find it, show the user a message saying it’s missing. This could be done by catching the FileNotFoundException produced here:

    // Here, we declare "throws IOException" to say someone else needs to handle it
    // In this particular case, IOException will only be thrown if an error occurs while reading the file
    public static void printFileToConsole() throws IOException {
        File nonExistent = new File("C:/nonexistentfile.txt");
        Scanner scanner = null;
        try {
            Scanner scanner = new Scanner(nonExistent);
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
        } catch (FileNotFoundException ex) {
            // The file wasn't found, show the user a message
            // Note use of "err" instead of "out", this is the error output
            System.err.println("File not found: " + nonExistent);
            // Here, we could recover by creating the file, for example
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }
    

    So there’s a few things to note here:

    1. We catch the FileNotFoundException and use a custom error message instead of printing the stack trace. Our error message is cleaner and more user-friendly than printing a stack trace. In GUI applications, the console may not even be visible to the user, so this may be code to show an error dialog to the user instead. Just because the file didn’t exist doesn’t mean we have to stop executing our code.
    2. We declare throws IOException in the method signature instead of catching it alongside the FileNotFoundException. In this particular case, the IOException will be thrown here if we fail to read the file even though it exists. For this method, we’re saying that handling errors we encounter while reading the file isn’t our responsibility. This is an example of how you can declare an irrecoverable error (by irrecoverable, I mean irrecoverable here, it may be recoverable somewhere further up, such as in the method that called printFileToConsole).
    3. I accidentally introduced the finally block here, so I’ll explain what it does. It guarantees that if the Scanner was opened and an error occurs while we’re reading the file, the Scanner will be closed. This is important for many reasons, most notably that if you don’t close it, Java will still have the lock on the file, and so you can’t open the file again without exiting the application.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have recently started to use Twitter Bootstrap and trying to understand how it
I'm trying to understand how to use PDO with a connection class. class db
I'm trying to use a solution for serializing exceptions using jaxb. ( http://forums.java.net/jive/thread.jspa?messageID=256122 )
i am trying to understand the use of exceptions in PHP.. How they work
Just trying to understand the behavior of java.lang.Object class. public class TypeCheck{ static void
I am learning Django and I am trying to understand the use of models.py
I'm trying to understand how to use firebug to debug my Javascript. So I
I am trying to understand how to use instance variable in Perl OO -
I am trying to understand how to use reference parameters. There are several examples
I'm trying to understand why one would use Spring Batch over a scripting language

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.