how to use multiple try catch and throw exeception - try-catch

try{
if ($originalfile=='sample_upload.csv')
) {
$out.='file uploaded';
}
$out.=__('MESSAGES.error_1')."\n";
$this->error($out);
return false;
....
// code to open file and read and save
}catch (\Exception $e){
}
If the file is with correct name still it puts error_1 message, I want if file is with wrong name it should exit and go to catch block or if it gets error further in reading and saving file it should again go to catch block.

Related

Check if file exists on Android device with Kotlin

I'm newbie in Android development and doing on my first Android project and faced with .txt file handling.
I succesfully created a txt file on Android Emulator, which is stored in: /storage/emulated/0/Android/data/com.example.test/files/test.txt
My problem is, I don't know how to test with code if this file exists. I write next few lines, which I found on the Internet:
fun checkIfFileExists() {
val fileName2 = "test.txt"
var file = File(filesDir, fileName2)
var fileExists = file.exists()
if(fileExists) {
println("File exists")
}
else {
println("File doesn't exists")
}
}
Function for file saving:
btnSave.setOnClickListener(View.OnClickListener {
val file:String = fileName.text.toString()
val data:String = fileData.text.toString()
val fileOutputStream:FileOutputStream
try {
fileOutputStream = openFileOutput(file, Context.MODE_PRIVATE)
fileOutputStream.write(data.toByteArray())
}catch (e: FileNotFoundException){
e.printStackTrace()
}catch (e: NumberFormatException){
e.printStackTrace()
}catch (e: IOException){
e.printStackTrace()
}catch (e: Exception){
e.printStackTrace()
}
Toast.makeText(applicationContext,"data save",Toast.LENGTH_LONG).show()
fileName.text.clear()
fileData.text.clear()
})
But it always prints "File doesn't exists", although I checked myself and file exists.
Hope someone knows what I did wrong.
You instantiated the file with only the file name and no path, so how can it know where to look? On Android you don't want to be working with the absolute paths but with what the Context gives you.
Not sure how you created your original file, but assuming it was saved to internal storage, you would do this (getFilesDir() is a Context method, so will be available if calling from an Activity):
var file = File(getFilesDir().getAbsolutePath(), fileName2)

Why groovy method doesn't print that file doesn't exist?

I have problem with my groovy script. I'm reading content from registerFile and I want to catch Exception when file is not found. Nevertheless below function doesn't throw exception even if registerfile does not exist, why?
Fragment of my code:
def registerFile
static void main(def args) {
Agent agent = new Agent()
agent.findSmth()
}
Agent() {
registerFile = new File(/path/toFile)
}
def findSmth() {
def s
try {
def lines = registerFile.readLines()
def numbers = lines.get(lines.size() - 1).findAll(/\d+/)*.toInteger()
s = numbers.get(numbers.size() - 1)
} catch (Exception e) {
println(e) //why not print that file doesn't exist?
} finally {
return s
}
}
I'm assuming that the above code is inside the class Agent.
As soon as you execute an operation on a non-existing file, an exception is thrown; so your catch statement should catch the Exception.
Are you sure that no such file exists in the path that you mentioned?

Groovy script to modify text file line by line

I have a input file from which a Groovy file reads input. Once a particular input is processed, Groovy script should be able to comment the input line it used and then move on.
File content:
1
2
3
When it processes line 1 and line 2, the input file will look as below:
'1
'2
3
By this way, if I re-run the Groovy, I would like to start from the line it stopped last time. If a input was used and it failed, that particular line shall not be commented (') so that a retry can be attempted.
Appreciate if you can help to draft a Groovy script.
Thanks
AFAIK in Groovy you can only append text at the end of the file.
Hence to add ' on each line when it is processed you need to rewrite the entire file.
You can use the follow approach but I only recommend you to use for a small files since you're loading all the lines in memory. In summary an approach for your question could be:
// open the file
def file = new File('/path/to/sample.txt')
// get all lines
def lines = file.readLines()
try{
// for each line
lines.eachWithIndex { line,index ->
// if line not starts with your comment "'"
if(!line.startsWith("'")){
// call your process and make your logic...
// but if it fails you've to throw an exception since
// you can not use 'break' within a closure
if(!yourProcess(line)) throw new Exception()
// line is processed so add the "'"
// to the current line
lines.set(index,"'${line}")
}
}
}catch(Exception e){
// you've to catch the exception in order
// to save the progress in the file
}
// join the lines and rewrite the file
file.text = lines.join(System.properties.'line.separator')
// define your process...
def yourProcess(line){
// I make a simple condition only to test...
return line.size() != 3
}
An optimal approach to avoid load all lines in memory for a large files is to use a reader to read the file contents, and a temporary file with a writer to write the result, and optimized version could be:
// open the file
def file = new File('/path/to/sample.txt')
// create the "processed" file
def resultFile = new File('/path/to/sampleProcessed.txt')
try{
// use a writer to write a result
resultFile.withWriter { writer ->
// read the file using a reader
file.withReader{ reader ->
while (line = reader.readLine()) {
// if line not starts with your comment "'"
if(!line.startsWith("'")){
// call your process and make your logic...
// but if it fails you've to throw an exception since
// you can not use 'break' within a closure
if(!yourProcess(line)) throw new Exception()
// line is processed so add the "'"
// to the current line, and writeit in the result file
writer << "'${line}" << System.properties.'line.separator'
}
}
}
}
}catch(Exception e){
// you've to catch the exception in order
// to save the progress in the file
}
// define your process...
def yourProcess(line){
// I make a simple condition only to test...
return line.size() != 3
}

Sahi: Try-catch can't handle 'The parameter passed to xyz was not found on the browser" error?

I run all my scripts through a .suite-file roughly in the following form:
_include("variables.sah");
_include("functions.sah");
$a = 0;
while($a<3) {
try {
_navigateTo($loginpage);
login($user, $password);
myFunction();
$a = 3
}
catch (e){
_navigateTo($loginpage);
login($user, $password);
//undo changes made by myFunction()
...
$a++;
if($a<3) {
_log("Try again");
}
else {
_log("Skip to next script");
}
}
}
function myFunction() {
//do this
...
}
Now all this runs perfectly fine, except for one thing: it doesn't repeat when it encounters a missing element which under normal circumstances would abort all scripts. It simply ignores the error and moves on to the next line of the suite. How do I make my script retry up to 2 times before moving on, if I don't know which part (if any) is going to fail and when?
Your code looks fine I guess.
One thing I can think of is that the exception is thrown in the catch block.
I made a simple script which works as intended:
var $errors = 0;
function trySet() {
try {
_setValue(_textbox("does not exist"), "");
} catch ($e) {
$errors++
_alert($errors);
}
}
for (var $i = 0; $i < 3; $i++) {
trySet();
}
Better figure out where exactly your script runs into problems and handle them with separate try-catch blocks accordingly. How you handle the exceptions is up to you but I guess it would be something like:
try {
login()
} catch ($e) {
// login failed, try again
}
try {
myfunction()
catch($e) {
revertMyFunction()
//try again
}
Maybe define your own exceptions to differently react to errors, have a look at this for more info on custom exceptions: Custom Exceptions in JavaScript
Regards
Wormi

Windows 8 StorageFile.GetFileFromPathAsync Using UNC Path

Has anyone EVER managed to use a windows 8 app to copy files from a unc dir to a local dir ?
According to the official documentation here
It is possible to connect to a UNC path
I am using the std FILE ACCESS sample and have changed one line of code to read as below
I have added all the capabilities
Added .txt as a file type
The UNC path is read write to everyone and is located on the same machine..
But I keep getting Access Denied Errors.
Can anyone possibly provide me with a working example
This is driving me mad and really questioning the whole point of win 8 dev for LOB apps.
TIA
private async void Initialize()
{
try
{
//sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename);
string myfile = #"\\ALL387\Temp\testfile.txt";
sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(myfile);
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}
I have sorted this out and the way I found best to do it was to create a folder object
enumnerate over the files in the folder object
copy the files one at a time to the local folder then access them
It seems that you can't open the files, but you can copy them. ( which was what I was trying to achieve in the first place )
Hope this helps
private async void Initialize()
{
try
{
var myfldr = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(#"\\ALL387\Temp");
var myfiles = await myfldr.GetFilesAsync();
foreach (StorageFile myfile in myfiles)
{
StorageFile fileCopy = await myfile.CopyAsync(KnownFolders.DocumentsLibrary, myfile.Name, NameCollisionOption.ReplaceExisting);
}
var dsd = await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var file in dsd)
{
StorageFile sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(file.Path);
}
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}

Resources