prinBalAgencyComm.sendKeys(testData.get("agencyCommissionPB"));
prinBalClientRem.sendKeys(Keys.TAB);
prinBalFrom2.sendKeys(testData.get("fromFB2")); //Locator not found
prinBalAgencyCommLast.sendKeys(testData.get("agencyCommissionLastPB")); //how to execute this line without fail
You can handle this by using try catch finally.
try{
//code that can result in an exception
prinBalAgencyComm.sendKeys(testData.get("agencyCommissionPB"));
prinBalClientRem.sendKeys(Keys.TAB);
prinBalFrom2.sendKeys(testData.get("fromFB2"));
}catch(Exception e)
{
//actions you want to take in case your locator isnt found or another exception occurs
System.out.println("Exception occured" + e.getMessage());
}finally
{ //the line to be executed without fail
prinBalAgencyCommLast.sendKeys(testData.get("agencyCommissionLastPB"));
}
you would have to implement a try/catch block
try {
element action
} catch (Exception e) {
//whatever you want to happen when it fails
}`
But I would ask myself why is the test not consistent with every run? Why should this step not pass every time?
One pattern you can use is:
try {}
catch {}
Place your offending code in the try block and any error code in the catch block.
If an exception is raised in the try, the catch block will be called instead of proceeding to the next line in the try
Related
In my framework - , Test & PageObjModel classes are there. incase any method is not executed because of wrong xpath or other any issue the Test is terminating but in the Report-Console it is showing all the Testcase are PASS.
Any issue in the Action methods of PageObjModel, some times it will skip that particular line of code and continue execution. sometimes entire test is terminating. in both the case Report-Console it is showing all the Testcase are PASS i.e No failures of Testcases.
Please have a look into below example of code and suggest me to fail the TC incase of failures.
I tried to include Assert.fail(), Assert.true(fail) in the "catch" block, though it is showing PASS results.
PageObjModel:
class A{
// list of xpaths
public static fibal String Login_xpath = "//*[#id='login'];
public void login(){
try{
// All Action methods are define here
}catch (Exception e){
e.printStackTrace();
//Assert.assertTrue(false);
Assert.fail();
} } }
Test class:
#Test
public void loginTest(){
//calling methods
xx.login();
}
This is just sample code. please help me where can I put Assertions to fail the TC when failure occurs in the code
If we are using try-catch in your code, please add throw as well. otherwise, it won't inform testng about the failure.
catch (AssertionError e) {
e.printStackTrace();
takeSnapShot(action);
throw e;
}
I'm still learning Kotlin and I just learned about the "use" and how it is a replacement for a try, catch and finally block.
However I am curious if it is possible to customize it's exception handling for example:
var connection: Connection? = null
try {
connection = dataSource.connection
connection.prepareStatement(query).execute()
} catch (e: SQLException) {
logger.log("Specific error for that query")
e.printStackTrace()
} finally {
if (connection != null && !connection.isClosed) {
connection.close()
}
}
That code is my current one, I have a specific error I would like to display on the catch, would that be possible using use?
This is my current use code:
dataSource.connection.use { connection ->
connection.prepareStatement(query).execute()
}
As commented by #Tenfour04, and from the documentation
[use] Executes the given block function on this resource and then closes it down correctly whether an exception is thrown or not.
In particular it is implemented like this:
public inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R {
var exception: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
exception = e
throw e
} finally {
this.closeFinally(exception)
}
}
That piece of code should look familiar if you're a Java developer, but basically it executes block passing this (i.e. the receiver object) as an argument to your block of code. At the end it closes the AutoCloseable resource. If at any point an exception is thrown (either inside block or while closing the resource), that exception is thrown back to the caller, i.e. your code.
As an edge case you could have 2 exceptions, one when executing block and one when closing the resource. This is handled by closeFinally (whose source is available in the same file linked above) and the exception thrown while closing the resource is added as a suppressed exception to the one thrown from block – that's because only up to 1 exception can be thrown by a method, so they had to choose which one to throw. The same actually applies to the try-with-resources statement in Java.
All I'm trying to do is verify a query.
'SELECT * from table_that_does_not_exist'
Without that erroring out, I'd like to know it failed so I can return a response that states "Error: table does not exist" or the generic error.
The simplest way to catch any sql syntax or query errors is to catch an Illuminate\Database\QueryException after providing closure to your query:
try {
$results = \DB::connection("example")
->select(\DB::raw("SELECT * FROM unknown_table"))
->first();
// Closures include ->first(), ->get(), ->pluck(), etc.
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
// Note any method of class PDOException can be called on $ex.
}
If there are any errors, the program will die(var_dump(...)) whatever it needs to.
Note: For namespacing, you need to first \ if the class is not included as a use statement.
Also for reference:
Laravel 5.5 API - Query Exception
Laravel 8.x API - Query Exception
Wrap the lines of code you wish to catch an exception on using try-catch statements
try
{
//write your codes here
}
catch(Exception $e)
{
dd($e->getMessage());
}
Do not forget to include the Exception class at the top of your controller by saying
Use Exception;
If you want to catch all types of database exceptions you can catch it on laravel Exception Handler
if ($exception instanceof \PDOException) {
# render a custom error
}
for more details about how to use laravel Exception Handler check https://laravel.com/docs/7.x/errors
Laravel 8.x
try {
$model->save(); // Use Eloquent: https://laravel.com/docs/8.x/eloquent
} catch (\Throwable $e) {
return 'My error message';
}
Note* Need to specify \Throwable $e no Throwable $e.
I made a test class against the repository methods shown below:
public void AddFile<TFileType>(TFileType FileToAdd) where TFileType : File
{
try
{
_session.Save(FileToAdd);
_session.Flush();
}
catch (Exception e)
{
if (e.InnerException.Message.Contains("Violation of UNIQUE KEY"))
throw new ArgumentException("Unique Name must be unique");
else
throw e;
}
}
public void RemoveFile(File FileToRemove)
{
_session.Delete(FileToRemove);
_session.Flush();
}
And the test class:
try
{
Data.File crashFile = new Data.File();
crashFile.UniqueName = "NonUniqueFileNameTest";
crashFile.Extension = ".abc";
repo.AddFile(crashFile);
Assert.Fail();
}
catch (Exception e)
{
Assert.IsInstanceOfType(e, typeof(ArgumentException));
}
// Clean up the file
Data.File removeFile = repo.GetFiles().Where(f => f.UniqueName == "NonUniqueFileNameTest").FirstOrDefault();
repo.RemoveFile(removeFile);
The test fails. When I step in to trace the problem, I found out that when I do the _session.flush() right after _session.delete(), it throws the exception, and if I look at the sql it does, it is actually submitting a "INSERT INTO" statement, which is exactly the sql that cause UNIQUE CONSTRAINT error. I tried to encapsulate both in transaction but still same problem happens. Anyone know the reason?
Edit
The other stay the same, only added Evict as suggested
public void AddFile<TFileType>(TFileType FileToAdd) where TFileType : File
{
try
{
_session.Save(FileToAdd);
_session.Flush();
}
catch (Exception e)
{
_session.Evict(FileToAdd);
if (e.InnerException.Message.Contains("Violation of UNIQUE KEY"))
throw new ArgumentException("Unique Name must be unique");
else
throw e;
}
}
No difference to the result.
Call _session.Evict(FileToAdd) in the catch block. Although the save fails, FileToAdd is still a transient object in the session and NH will attempt to persist (insert) it the next time the session is flushed.
NHibernate Manual "Best practices" Chapter 22:
This is more of a necessary practice than a "best" practice. When
an exception occurs, roll back the ITransaction and close the ISession.
If you don't, NHibernate can't guarantee that in-memory state
accurately represents persistent state. As a special case of this,
do not use ISession.Load() to determine if an instance with the given
identifier exists on the database; use Get() or a query instead.
I have the following code
Try
'Some code that causes exception
Catch ex as ExceptionType1
'Handle Section - 1
Catch ex as ExceptionType2
'Handle section - 2
Catch ex as ExceptionType3
'Handle section - 3
Finally
' Clean up
End Try
Suppose ExceptionType1 is thrown by the code which is handled by section - 1. After handling that in section-1, can I have control passed to section-2/section-3? Is that possible?
Change the code to catch all the exceptions in one block and determine the type and execution path from there.
You could call functions in the exception handlers.
Try
'Some code that causes exception'
Catch ex as ExceptionType1
handler_1()
handler_2()
handler_3()
Catch ex as ExceptionType2
handler_2()
handler_3()
Catch ex as ExceptionType3
handler_3()
Finally
handler_4()
End Try
You haven't specified a language, and i don't know the language, so i answer generally.
You can't do that. If you want to have common code, put that either into finally, or if it only needs to be executed for some catching cases, you can copy that code into the respective cases. If the code is bigger and you want to avoid redundancy, you can put it into a function of its own. If that would reduce the readability of your code, you can nest your try/catch blocks (at least in Java and C++. I don't know about your language). Here is an example in Java:
class ThrowingException {
public static void main(String... args) {
try {
try {
throw new RuntimeException();
} catch(RuntimeException e) {
System.out.println("Hi 1, handling RuntimeException..");
throw e;
} finally {
System.out.println("finally 1");
}
} catch(Exception e) {
System.out.println("Hi 2, handling Exception..");
} finally {
System.out.println("finally 2");
}
}
}
This will print out:
Hi 1, handling RuntimeException..
finally 1
Hi 2, handling Exception..
finally 2
put your common code into the outer catch block. Doing it using the nested version also handles cases where an exception occurs without you explicitly re-throwing the old in a catch block. It may fit to what you want even better, but it may also not.
I think you could get the behavior you want if you do nested try blocks. Once an exception is thrown, execution goes to the catch block. If nothing is rethrown, it moves on to finally.