ConnectException: Connection Refused on Java
Tthe standard library of the Java programming language includes a number of functions that integrate tasks that formerly required an onerous amount of software engineering into its basic structure. Among these functions are those that establish networking socket connections to other machines and servers. A variety of problems could cause these connections to be refused. If you want to make quality Java programs, you need to correctly code your application to handle refused connections without crashing the program.
Instructions
-
-
1
Begin the section of your program that will create a socket connection by writing a "try" function, which will contain the code that creates the connection. Create the function by writing" try {
your_connection_code
}"
-
2
Add the code to connect to the target machine or server between the brackets that demarcate your "try" function.
-
-
3
Add a "catch" function immediately after the closing bracket of the "try" function. The code should look something like this:
"try {
your_connection_code
} catch (Exception e){
catch_function_code
}"
The "catch" function will engage if the connection your "try" function tries to establish is refused.
-
4
Write what you want your program to do in case the connection is refused between the brackets of the "catch" function. By catching and handling the exception a connection error throws, the program can continue to function instead of crashing on the spot.
-
1
Tips & Warnings
Java will store the exact exception a connection error throws in the exception object "e" if you use the exact code for declarin 3g the "catch" function that this article used. You can also give the object another name by simply using another term after the "Exception" in the parenthesis following the "catch" declaration, but "e" is a conventional name to use for an exception.
References
- Photo Credit Stockbyte/Stockbyte/Getty Images