For a computer networking course I was given a project to make a Mail User Agent. We were given a few completed classes, but one of them is giving an error. Here is the part of code in question:

try {
		Envelope envelope = new Envelope(mailMessage, 
						 serverField.getText());
	    } catch (UnknownHostException e) {
		/* If there is an error, do not go further */
		return;
	    }
	    try {
		SMTPConnection connection = new SMTPConnection(envelope);
		connection.send(envelope);
		connection.close();
	    } catch (IOException error) {
		System.out.println("Sending failed: " + error);
		return;
	    }
	    System.out.println("Mail sent succesfully!");

The error is that it cannot find symbol "envelope in the second try block. Does the scope of try catch not extend outside? Any suggestions on how to go about fixing this?

krusso88
Deleted Member

For a computer networking course I was given a project to make a Mail User Agent. We were given a few completed classes, but one of them is giving an error. Here is the part of code in question:

try {
		Envelope envelope = new Envelope(mailMessage, 
						 serverField.getText());
	    } catch (UnknownHostException e) {
		/* If there is an error, do not go further */
		return;
	    }
	    try {
		SMTPConnection connection = new SMTPConnection(envelope);
		connection.send(envelope);
		connection.close();
	    } catch (IOException error) {
		System.out.println("Sending failed: " + error);
		return;
	    }
	    System.out.println("Mail sent succesfully!");

The error is that it cannot find symbol "envelope in the second try block. Does the scope of try catch not extend outside? Any suggestions on how to go about fixing this?

envelope is declared inside the first Try block so its scope finish there.
If you wish to use envelope in the second try block. Declare outside the try block.

Envelope envelope=null;
try {
		envelope = new Envelope(mailMessage, 
						 serverField.getText());
	    } catch (UnknownHostException e) {
		/* If there is an error, do not go further */
		return;
	    }
	    try {
		SMTPConnection connection = new SMTPConnection(envelope);
		connection.send(envelope);
		connection.close();
	    } catch (IOException error) {
		System.out.println("Sending failed: " + error);
		return;
	    }
	    System.out.println("Mail sent succesfully!");
This question has already been answered. Start a new discussion instead.