New to Java, so please bear with me:
(and please note that this qestion is about Java Exceptions, not Jsoup)
when using Jsoup in order to get Html page: (Jsoup.connect(current_url._name).get();) , I tried to catch all possible 5 exceptions according to the Jsoup documentation: here
the program works fine with good URLs, but when I intentionally misspelled 1 URL to check what happens, I was surprised to see that the exception wasn't catch, instead the program start running, then the "Build failed"?
when only building the program there is no failure, so I think it isn't really
build issue.
here is the code:
// load html and check them:
for(URL current_url : URLs)
{
// no keyword - all getting 'yes'
if(keywords.isEmpty())
{
current_url._stat = URL_stat.YES;
}
// there are keywords - get pages and check them
else
{
Document html_doc;
// try to get document and catch all errors
try
{
html_doc = Jsoup.connect(current_url._name).get();
}
catch(MalformedURLException e)
{
System.out.println("the request " + current_url._name +
" URL is malformed");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(HttpStatusException e)
{
System.out.println("page " + current_url._name + " response"
+ " is not ok");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(UnsupportedMimeTypeException e)
{
System.out.println("page " + current_url._name+ " mime type"
+ " is not supported");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(SocketTimeoutException e)
{
System.out.println("connection to " + current_url._name +
" times out");
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
catch(IOException e)
{
System.out.println("an error occurred while getting page "
+ current_url._name);
System.out.println(e.getMessage());
current_url._stat = URL_stat.ERROR;
}
// check if document has paragraphs, if not mark - no
}
}
and the output:
Exception in thread "main" java.lang.IllegalArgumentException: Malformed URL: ttp://cooking.nytimes.com/topics/what-to-cook-this-week
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:76)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:36)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at ex2.Ex2.main(Ex2.java:123)
Caused by: java.net.MalformedURLException: unknown protocol: ttp
at java.net.URL.<init>(URL.java:600)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:74)
... 3 more
C:\Users\Administrator\AppData\Local\NetBeans\Cache\8.2\executor- snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
Thanks,
It is because the first exception being thrown is an IllegalArgumentException, which you have not defined in any of your catch clauses, thus preventing you from getting your custom error messages in any other catch blocks.
Related
I am trying to get the PSQLException exception, however it tells me that this block cannot be reached, does anyone know why? I mean, I can't run or anything, Eclipse marks it as an error. However, if, for example, I put Exception e, instead of PSQLException e, it does not give an error.
#DeleteMapping("/delete/{pais_id}")
public Resultado<Pais> eliminaPais(#PathVariable("pais_id") Long pais_id, HttpServletResponse response) {
Resultado<Pais> res = new Resultado<>();
try {
Optional<Pais> existePais = paisService.getFindById(pais_id);
if (existePais.isPresent()) {
if (pais_id != null) {
// monedaService.setANullPais(pais_id);
try{
paisService.getEliminaPais(pais_id);
res.setCodigo(200);
res.setMensaje("El país " + existePais.get().getNombre() + " ha sido eliminado");
res.setDatos(existePais.get());
}catch(PSQLException e) { //HERE
res.setCodigo(400);
res.setMensaje("El país no " + existePais.get().getNombre() + " ha sido eliminado");
res.setDatos(null);
}
}
} else {
res.setSuccess(false);
res.setMensaje("Se ha producido un error, el ID proporcionado no existe " + pais_id);
res.setCodigo(400);
}
} catch (Exception e) {
res.setSuccess(false);
res.setMensaje("Se ha producido un error: " + e.getMessage());
res.setCodigo(400);
}
response.setStatus(res.getCodigo());
return res;
}
PSQLException is a checked exception. That means methods which throw that exception are required to document it in their signature. The compiler has detected that no code in your try block throws that type of exception. It knows that the catch block is redundant and is likely a user error, so it produces a failure so you can fix it.
Exception is a broader classification and includes the set of all unchecked exceptions, which are not required to be documented in a method signature. In this case, the compiler doesn't know exactly what might be thrown, but it knows that something might be. So in this case, the catch block is not (necessarily) redundant, and so it will not report the same failure.
Since it is an checked exception, you are trying to catch an exception which is never thrown.
You try block code should throw an Checked exception then only you can catch it.
In your case that is PSQLException.
I've been getting com.google.gson.JsonSyntaxException from calling Gson.fromJson(), so added a catch(Exception) logic, but the error is never getting caught and just getting thrown!
Here's what I have:
Request request = new Request.Builder()
.url(getOrderUrlWithId)
.get()
.build();
try {
Response response = this.okHttpClient.newCall(request).execute();
GetOrderResult orderResult = gson.fromJson(gson.toJson(response.body().string()), GetOrderResult.class);
response.close();
} catch (IOException e) {
log.error("Error retrieving order : " + e.getMessage(), e);
throw new RuntimeException(e);
} catch (Exception e) {
log.error("Error happening for client PO: " + clientPO, e);
return null;
}
When I run the test I get "com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
"
Why isn't the error getting caught?
Here's the Stack trace:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:927)
at com.google.gson.Gson.fromJson(Gson.java:892)
at com.google.gson.Gson.fromJson(Gson.java:841)
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.hub.fulfill.circlegraphics.getOrdersByCgOrderId(CircleGraphicsApi.java:164)
You need to catch JsonSyntaxException like this
For Kotlin
catch(e: JsonSyntaxException){
//show toast/snackabar/log here
}
For Java
catch(JsonSyntaxException e){
//show toast/snackabar/log here
}
Earlier I was also catching java.lang.IllegalStateException but it didn't worked.
Seems the root exception here is JsonSyntaxException and thus, we need to catch this one.
It worked for me!
when(...).thenReturn(null) points that you use some mocking library (jMock, Mockery or simular). And you define that if fromJson("test", Fulfillment.class) is called mock should return null. Actual method fromJson is not invoked as you already defined result.
If you want expection to be thrown, then remove line
when(gson.fromJson("test", Fulfillment.class)).thenReturn(null);
Figured it out. So turns out #Slf4j's log.error() call shows the exception as an error in Google StackDriver, hence telling me I've been getting millions of errors.
This code is written to get the error reported in console if WebElement is not found on page. It fails on try block but doesn't go to catch.
I have tried different tweaks and tricks but its not working, please share what am I missing:
Code:
public class GetElement extends TestBase{
WebDriverWait wdw = new WebDriverWait(driver, 10);
public WebElement getElement(WebElement element) {
try {
System.out.println("\n" + "==============" + "\n"
+ "inside try of gE" + "\n" + "===================");
return wdw.until(ExpectedConditions.elementToBeClickable(element));
} catch (NoSuchElementException | TimeoutException ex) {
System.out.println("\n" + "==============" + "\n"
+ element.getText()
+ " Element not or wasnt clickable found on page" + "\n"
+ driver.getCurrentUrl() + "\n" + "===================");
}
System.out.println("\n" + "==============" + "\n"
+ "Element will be returned as null"+ "\n" + "===================");
return null;
}
}
here TestBase initializes the WebDriver
Exception that I get often is (often, because I was also getting time out but then I increased time):
org.openqa.selenium.NoSuchElementException: no such element
(Session info: chrome=38.0.2125.111)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.3 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 137 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'
Several possobilities.
The exception thrown is org.openqa.selenium.NoSuchElementException. Because NoSuchElementException is a fairly common name, I suspect in your code the NoSuchElementException isn't from your org.openqa.selenium package.
The exception is thrown from outside of the try block at all.
If you still cannot work out where it's from, add a catch block to catch all Exception after and see if the exception is correctly triggered in your try block.
What Alex said is right, your catch block catches java.util.NoSuchElementException - from , but you must be actually getting a
org.openqa.selenium.NoSuchElementException.
Try this catch block:
catch(org.openqa.selenium.NoSuchElementException e| TimeoutException ex){
I have a try/catch thing set up where it will catch all exceptions and then display the error.
Here is my code:
try {
//CODE THAT COULD ERROR HERE
} catch (final Exception e) {
System.err.println("Unexpected error: " + e.getStackTrace()[0]);
}
The above code gives me the LAST class that had the error. How do I detect the LAST class of MY PROGRAM that had the error?
Example Output: "Unexpected error: package.ClassName.method(ClassName.java:46)"
I want it to output the line of my program that had the error, not the line of a built-in java class that error-ed because of my program.
e.printStackTrace()
might make you happier. Or print the top of the array of stack trace entries available from the appropriate method.
http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getStackTrace()
returns them. The first one is what you are asking for.
You can use getStackTrace to get an array of StackTraceElement instances, and filter that based on your package and/or class names (using getClassName for each element, which gives you the fully-qualified class name for that stack trace frame). That would let you winnow it down to your code rather than the JDK class the exception originated in.
try {
//error producing code
} catch (Exception e) {
for (StackTraceElement s : e.getStackTrace()) {
if (!s.getClassName().startsWith("java.")) {
System.out.println("file name: " + s.getFileName());
System.out.println("class name: " + s.getClassName());
System.out.println("method name: " + s.getMethodName());
System.out.println("line number: " + s.getLineNumber());
System.out.println();
//break; // will be the highest non java package...
}
}
}
You of course could switch it to be package specific so if (s.getClassName().startsWith("com.company")) { so it wont return for a third party library or something in the sun package or other non java package.
I've some problem printing the exception stack trace for Alfresco Exception.
On debug mode, step by step under Eclipse IDE I'm able to see the message when the exception is raised inspecting the Exception object but, when I send the error message to console output it's always null.
The exception is raised by this instruction:
try {
UpdateResult[] results = WebServiceFactory.getRepositoryService().update(cml);
}
catch (Exception ex) {
System.out.println(" " + ex.getStackTrace());
System.out.println("ERROR - createContent : " + ex.getMessage());
}
(in that case I tryed to write on a folder that not exists on repository) and inspecting the ex object on eclipse I can see the message:
java.lang.IllegalStateException: Failed to resolve to a single NodeRef with parameters (store=workspace:SpacesStore uuid=null path=/app:company_home/cm:UploadFromJava), found 0 nodes.
but ex.getMessage() returns null
Anyone could help me?
thanks,
Andrea
Implementing a method in this way:
NamedValue setNameProperty(String name) throws AlfrescoRuntimeException
{
try {
return Utils.createNamedValue(Constants.PROP_NAME, name);
}
catch (Exception ex) {
throw new AlfrescoRuntimeException(ex.getMessage());
}
}
The message is correclty printed with e.printStackTrace();
Try to replace your package in the log4j.properties from debug to error