0
# Exception Handling
1
2
The `ArduinoException` class provides comprehensive error management for Arduino communication with multilingual support. It handles specific exceptions that may occur during serial communication and provides detailed error messages in both English and Spanish.
3
4
## ArduinoException Class
5
6
```java { .api }
7
public class ArduinoException extends Exception {
8
public ArduinoException(String portName, String methodName, String exceptionType);
9
}
10
```
11
12
Creates a new Arduino-specific exception with detailed context information.
13
14
**Parameters:**
15
- `portName` - Name of the COM port where the exception occurred
16
- `methodName` - Method that triggered the exception
17
- `exceptionType` - Type of exception (use predefined constants)
18
19
## Language Configuration
20
21
```java { .api }
22
public static void setLanguage(boolean englishLanguage);
23
```
24
25
Sets the language for error messages.
26
27
**Parameters:**
28
- `englishLanguage` - `true` for English, `false` for Spanish (default)
29
30
**Usage Example:**
31
32
```java
33
// Set language to English
34
ArduinoException.setLanguage(true);
35
36
// Set language to Spanish
37
ArduinoException.setLanguage(false);
38
```
39
40
## Error Message Retrieval
41
42
```java { .api }
43
public static String getExceptionMessage(String exceptionType);
44
```
45
46
Retrieves the localized error message for a specific exception type.
47
48
**Parameters:**
49
- `exceptionType` - Exception type constant
50
51
**Returns:** Localized error message string
52
53
## Exception Information Access
54
55
```java { .api }
56
public static String getExceptionType();
57
public static void setExceptionType(String exceptionType);
58
public static String getMethodName();
59
public static void setMethodName(String methodName);
60
public static String getPortName();
61
public static void setPortName(String portName);
62
```
63
64
Methods for accessing and setting exception context information.
65
66
## Exception Type Constants
67
68
### Port-Related Exceptions
69
70
```java { .api }
71
public static final String TYPE_PORT_ALREADY_OPENED = "The port you are trying to open is being used by another device";
72
public static final String TYPE_PORT_NOT_OPENED = "Port not opened";
73
public static final String TYPE_NO_ARDUINO_AT_PORT = "No Arduino found connected to this port. Please check the port to which Arduino is connected";
74
public static final String TYPE_NO_SERIAL_PORT = "No Arduino found connected to this computer. Please connect Arduino to the PC via USB";
75
public static final String TYPE_PORT_USED_BY_OTHER_APP = "Unable to connect. This port is already in use by another application";
76
```
77
78
### Connection-Related Exceptions
79
80
```java { .api }
81
public static final String TYPE_RXTX_EXCEPTION = "Cannot start the connection with Arduino twice";
82
public static final String TYPE_NO_ARDUINO_CONNECTION = "No connection has been established with Arduino. Please use one of the methods arduinoRX(), arduinoTX(), or arduinoRXTX()";
83
public static final String TYPE_KILL_ARDUINO_CONNECTION = "Cannot terminate the connection with Arduino if it was not started";
84
public static final String TYPE_CLOSE_PORT = "Error terminating the connection with Arduino";
85
```
86
87
### Data Transmission Exceptions
88
89
```java { .api }
90
public static final String TYPE_SEND_DATA = "This method cannot be used if the connection to Arduino was started with the arduinoRX() method, which is only for receiving data";
91
public static final String TYPE_SEND_DATA_ERROR = "Error sending data";
92
public static final String TYPE_WRONG_SEND_DATA_CONNECTION = "The sendData() method cannot be used if the connection to Arduino was started with the arduinoRX() method, which is only for receiving data";
93
```
94
95
### Data Reception Exceptions
96
97
```java { .api }
98
public static final String TYPE_RECEIVE_DATA = "The receiveData() method cannot be used if the connection to Arduino was started with the ArduinoTX() method, which is only for sending data";
99
public static final String TYPE_NO_EVENT_LISTENER = "No EventListener has been added to the PanamaHitek_Arduino class";
100
```
101
102
## Spanish Error Messages
103
104
All exception types have corresponding Spanish translations with `_ES` suffix:
105
106
```java { .api }
107
public static final String TYPE_PORT_ALREADY_OPENED_ES = "El puerto que intenta abrir está siendo utilizado por otro dispositivo";
108
public static final String TYPE_PORT_NOT_OPENED_ES = "Puerto no abierto";
109
public static final String TYPE_NO_ARDUINO_AT_PORT_ES = "No se ha encontrado ningún Arduino conectado a este puerto. Verifique el puerto en el que está conectado Arduino";
110
// ... and so on for all exception types
111
```
112
113
## Usage Examples
114
115
### Basic Exception Handling
116
117
```java
118
import com.panamahitek.PanamaHitek_Arduino;
119
import com.panamahitek.ArduinoException;
120
121
public class ExceptionHandlingExample {
122
123
public void connectWithErrorHandling() {
124
// Set language preference
125
ArduinoException.setLanguage(true); // English
126
127
PanamaHitek_Arduino arduino = new PanamaHitek_Arduino();
128
129
try {
130
arduino.arduinoTX("COM3", 9600);
131
arduino.sendData("Hello Arduino!");
132
133
} catch (ArduinoException ex) {
134
System.err.println("Arduino Exception Details:");
135
System.err.println("Port: " + ArduinoException.getPortName());
136
System.err.println("Method: " + ArduinoException.getMethodName());
137
System.err.println("Type: " + ArduinoException.getExceptionType());
138
System.err.println("Message: " + ex.getMessage());
139
140
// Handle specific exception types
141
String exceptionType = ArduinoException.getExceptionType();
142
switch (exceptionType) {
143
case ArduinoException.TYPE_NO_SERIAL_PORT:
144
System.err.println("Please connect Arduino via USB");
145
break;
146
case ArduinoException.TYPE_PORT_ALREADY_OPENED:
147
System.err.println("Close other applications using this port");
148
break;
149
case ArduinoException.TYPE_NO_ARDUINO_AT_PORT:
150
System.err.println("Check Arduino connection and port");
151
break;
152
}
153
}
154
}
155
}
156
```
157
158
### Multilingual Error Handling
159
160
```java
161
public class MultilingualErrorHandling {
162
163
public void handleErrorsInSpanish() {
164
// Configure for Spanish error messages
165
ArduinoException.setLanguage(false);
166
167
try {
168
PanamaHitek_Arduino arduino = new PanamaHitek_Arduino();
169
arduino.arduinoRX("COM99", 9600, null); // Invalid port
170
171
} catch (ArduinoException ex) {
172
// Error messages will be in Spanish
173
System.err.println("Error en español: " + ex.getMessage());
174
}
175
}
176
177
public void handleErrorsInEnglish() {
178
// Configure for English error messages
179
ArduinoException.setLanguage(true);
180
181
try {
182
PanamaHitek_Arduino arduino = new PanamaHitek_Arduino();
183
arduino.sendData("data"); // No connection established
184
185
} catch (ArduinoException ex) {
186
// Error messages will be in English
187
System.err.println("English error: " + ex.getMessage());
188
}
189
}
190
}
191
```
192
193
### Custom Exception Handling
194
195
```java
196
public class CustomExceptionHandling {
197
198
public void createCustomException() {
199
try {
200
// Simulate a custom error scenario
201
throw new ArduinoException("COM3", "customMethod",
202
ArduinoException.TYPE_PORT_USED_BY_OTHER_APP);
203
204
} catch (ArduinoException ex) {
205
// Get localized error message
206
String localizedMessage = ArduinoException.getExceptionMessage(
207
ArduinoException.TYPE_PORT_USED_BY_OTHER_APP);
208
209
System.err.println("Localized message: " + localizedMessage);
210
System.err.println("Full exception: " + ex.getMessage());
211
}
212
}
213
}
214
```
215
216
### Comprehensive Error Recovery
217
218
```java
219
public class ErrorRecoveryExample {
220
221
private PanamaHitek_Arduino arduino;
222
private String[] possiblePorts = {"COM3", "COM4", "COM5", "/dev/ttyUSB0", "/dev/ttyACM0"};
223
224
public boolean connectWithRetry() {
225
ArduinoException.setLanguage(true);
226
arduino = new PanamaHitek_Arduino();
227
228
for (String port : possiblePorts) {
229
try {
230
System.out.println("Trying port: " + port);
231
arduino.arduinoRXTX(port, 9600, null);
232
System.out.println("Successfully connected to: " + port);
233
return true;
234
235
} catch (ArduinoException ex) {
236
String exceptionType = ArduinoException.getExceptionType();
237
238
switch (exceptionType) {
239
case ArduinoException.TYPE_NO_ARDUINO_AT_PORT:
240
System.out.println("No Arduino at " + port + ", trying next port...");
241
break;
242
243
case ArduinoException.TYPE_PORT_ALREADY_OPENED:
244
System.err.println("Port " + port + " is in use, trying next port...");
245
break;
246
247
case ArduinoException.TYPE_NO_SERIAL_PORT:
248
System.err.println("No serial ports available");
249
return false;
250
251
default:
252
System.err.println("Unexpected error: " + ex.getMessage());
253
break;
254
}
255
}
256
}
257
258
System.err.println("Failed to connect to any port");
259
return false;
260
}
261
}
262
```
263
264
## Best Practices
265
266
1. **Always set language preference** before performing Arduino operations
267
2. **Use specific exception type constants** for programmatic error handling
268
3. **Check exception context** using static getter methods for debugging
269
4. **Implement retry logic** for common connectivity issues
270
5. **Provide user-friendly error messages** based on exception types
271
6. **Clean up resources** properly in finally blocks or try-with-resources when applicable