Ideas for syntax for error handling similar to Rust (no exceptions)?

I'm looking for the most ergonomic syntax for error handling for my lang.

I wish to support error handling alike Rust/Swift, where there is required to use the Result<Ok, Err> enum. Now, the thing with that is how verbose it become in use. I wish to use the lang for quick data exploration and scripting. This is what I have in mind:

  • Errors are first class values. Everywhere you could return a value as normal, it could be a error:

&#8203;

return 1 //OK
fail 1 //Error
  • All functions have implicit a Result<Ok, Err> annotation:

&#8203;

fn open(file:Str) = File //sugar for:
fn open(file:Str) = Result&lt;File, Err (type infered)&gt; //but the user can override:
fn open(file:Str) = Result&lt;File, IOErr&gt;
  • Errors are propagated when not captured!:

&#8203;

fn div(x:Int) = x / 0
fn sum_div(x:Int) = div(x) + x //the error here buble up. 
sum_div(1) //and will show here

VS:

fn div(x:Dec) = x / 0
fn sum_div(x:Dec) = Dec
    r, err := div(x) //error is captured here. Not bubble up
sum_div(1) 

This is exactly alike normal values. A value can bubble up in the calls. Because errors are values, it is the same. It mean the functions are desugared to handle the error like manually will do a programmer.

----

Now, i think this are the possibilities:

  • All happy paths, the errors bubble up until is catch by the global handler. //Solved, I think
  • Return up 1 level in the stack //Solved, I think:

&#8203;

// A full program, only happy paths
StdIn | lex | parse | compile
  • Handle the error, resolve or give context (GO style is fine):

&#8203;

fn div(x:Dec) = Dec do
  x ! err = x / 0
  if err then fail "Divided by zero" else x
  • Take action if anything cause error (using exceptions is best in this case):

&#8203;

db = sqlite.open(..)
tx = db.begin_transaction()
//only caring to handle inside transaction
try
    db.insert(..)
    ...
catch
    tx.roolback()
tx.commit()

----

Now, I wish exist a way to merge the Ok and the Err parts that look logical. IFs as in GO are disconnected. You could ignore the IF or put it after take the OK value, need static analysis to warn the user. Using exception is ok if you only care if ANYTHING cause an error. So I think:

f ! err = open("a.txt") catch do // force to add catch in the line where ! err hap
... keep reading on reddit ➑

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/mamcx
πŸ“…︎ Oct 16 2019
🚨︎ report
Mysterious exception handling syntax

I just ran into a problem with the logging in my Python script. I stepped into config.py and found that my exception was raised form the following snippet:

​                    except Exception as e:
                        if 'target not configured yet' in str(e.__cause__):
                            deferred.append(name)
                        else:
                            raise ValueError('Unable to configure handler '
                                             '%r' % name) from e

All I saw when I ran my script was the "Unable to configure handler" message, with no underlying reason.

I'm not familiar with the use of "from" in this context. What is it for? And is there a way for me to examine the exception object (e) from inside my script? I'm guessing that the "from" clause gives me access to the underlying exception in the same way that an Exception object in C++ or C# has an InnerException property.

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/CedricCicada
πŸ“…︎ Aug 28 2018
🚨︎ report
Salesforce Development Tutorial - The Complete Guide to Exception Handling in Apex and LWC's (How to Produce Higher Quality User Experiences and Integrations with External Systems)

Hey there everyone! At the community's request, this week I have created a tutorial over exception handling in both Apex and Lightning Web Components.

Exception Handling is extremely important and, in my experience it's one of the most frequently overlooked areas of development in the Salesforce Ecosystem. If you've ever had users complain about ugly looking errors, inconsistent user experiences on custom components or you have integrations with external systems that fail with no warning, no safety net and no logging, chances are your code is not implementing exception handling anywhere in it. The code (or config) can fail in so many ways that you are unlikely to be able to imagine while building or testing it and exception handling helps ensure you deal with those unforeseen edge cases among other things!

The Tutorial Covers The Following Topics:

1:27 - What is an Exception and Why care about them?
2:27 - Examples of why you should use exception handling
5:42 - Apex Trigger exception handling example
8:50 - Try/Catch/Finally block explanation
14:48 - Why to use specific exception types in Catch Blocks
21:50 - The exceptions Salesforce won't let you handle yourself
25:14 - Handling errors in LWC's
36:27 - How to Create and When to use Custom Apex Exceptions
41:49 - Why use custom exceptions instead of returning strings
48:39 - How to handle exceptions in JavaScript
50:25 - Creating a try/catch/finally block to handle errors in JS
53:41 - Creating a custom exception type in JavaScript

Link to the Full Tutorial Video: Salesforce Development Tutorial - The Complete Guide to Exception Handling in Apex and LWC's

Hopefully this helps many

... keep reading on reddit ➑

πŸ‘︎ 39
πŸ’¬︎
πŸ‘€︎ u/BigIVIO
πŸ“…︎ Jan 24 2022
🚨︎ report
Try/Catch Exception Handling Question

I'm working on a project for school and I've been having a lot of trouble understanding what I'm doing wrong. I don't have any experience in Powershell so I'd really appreciate any advice/help.

That task that is giving me trouble is this: Apply exception handling using try-catch for System.OutOfMemoryException.

Here is what I've done so far: https://pastebin.com/gLC69sr6

Here are the instructions for the task:

A.Β Β Create a PowerShell script named β€œprompts.ps1” within the β€œRequirements1” folder. For the first line, create a comment and include your first and last name along with your student ID.

Note: The remainder of this task should be completed within the same script file, prompts.ps1.

B.Β Β Create a β€œswitch” statement that continues to prompt a user by doing each of the following activities, until a user presses key 5:

1.Β Β Using a regular expression, list files within the Requirements1 folder, with the .log file extension and redirect the results to a new file called β€œDailyLog.txt” within the same directory without overwriting existing data. Each time the user selects this prompt, the current date should precede the listing. (User presses key 1.)

2.Β Β List the files inside the β€œRequirements1” folder in tabular format, sorted in ascending alphabetical order. Direct the output into a new file called β€œC916contents.txt” found in your β€œRequirements1” folder. (User presses key 2.)

3.Β Β List the current CPU and memory usage. (User presses key 3.)

4.Β Β List all the different running processes inside your system. Sort the output by virtual size used least to greatest, and display it in grid format. (User presses key 4.)

5.Β Β Exit the script execution. (User presses key 5.)

C.Β Β Apply scripting standards throughout your script, including the addition of comments that describe the behavior of each of parts B1–B5.

D.Β Β Apply exception handling using try-catch for System.OutOfMemoryException.

E.Β Β Run your script and take a screenshot of the user results when each prompt (parts B3–B4) is chosen. Save each screenshot within the β€œRequirements1” folder. Compress all files (original and new) within the folder to a ZIP archive.

F.Β Β When you are ready to submit your final script, run the Get-FileHash cmdlet against the β€œRequirements1” ZIP archive. Note that hash value and place it into the comment section when you submit your task.

Furthermore, I've been given sample code that I am expected to follow, but plug in upd

... keep reading on reddit ➑

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/axshii99
πŸ“…︎ Jan 16 2022
🚨︎ report
exception handling (Skyrim)?

if you know Skyrim (game), in legendry edition if you load a corrupt file the game crashes, while in special edition it tells you the file is corrupt and returns you to the main menu, is this an example of an exception handling?

*note: I started learning newly, so I don't have enough knowledge to know for sure.

πŸ‘︎ 8
πŸ’¬︎
πŸ“…︎ Jan 11 2022
🚨︎ report
Exception handling in async task

This code works:

public string Version =&gt; GetVersionAsync().Result;



		private static async Task&lt;string&gt; GetVersionAsync()
		{

			var version = Version();
			Logger.LogDebug($"Version: {version} ");

			return version;
                }

This code does not work and UI freezes when it is executed:

public string Version =&gt; GetVersionAsync().Result;





		private static async Task&lt;string&gt; GetVersionAsync()
		{
			try
			{
				var version = Version();
				Logger.LogDebug($"Version: {version} ");

				return version;
			}
			catch (Exception ex)
			{
				Logger.LogDebug(ex);
				return ex.ToString();
			}
                }

Version() tries to connect using a localhost URL. If this connection fails and we cannot get the version I want catch block to be executed but nothing happens and UI freezes.

πŸ‘︎ 13
πŸ’¬︎
πŸ‘€︎ u/prayank_gahlot
πŸ“…︎ Dec 25 2021
🚨︎ report
How to debug Coroutines Exception Handling
πŸ‘︎ 106
πŸ’¬︎
πŸ‘€︎ u/phileo99
πŸ“…︎ Jan 03 2022
🚨︎ report
Handling Errors in Flow so they don't send exception email

Is it possible to handle an error in a flow such that an email is not sent for a specific fault path? I have tried a couple solutions I saw on forums (using a decision element) but haven't been able to get it stop sending the error email.

πŸ‘︎ 12
πŸ’¬︎
πŸ‘€︎ u/OwnTop4067
πŸ“…︎ Dec 18 2021
🚨︎ report
Differences between Exception handling classes

Hello, everyone. Currently I am learning about JDBC and noticed that in different examples on the internet, different classes are inserted in catch ().

Could someone tell what are the differences between Exception e , SQLException e and Throwable e ?

Thank you.

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/Mykoliux-1
πŸ“…︎ Jan 11 2022
🚨︎ report
Handling same exception (with different msg) thrown by different methods & functions?

I have multiple functions and methods which needs to throw the same exceptions, only difference is that the error messages will be different based on the API request it makes to different API endpoints.

Normal way to do this would be like:

def method1(path, item):
    try:
        client.call(&lt;API endpoint/get&gt;)
    except InvalidRequest:
        print("Invalid Path! The path {path} was not found.")
    except Forbidden:
        print(f'\nPermission denied! You do not have access tothe path: {path}')
    except InvalidPath:
        print(f'\nInvalid Path! The path {path} was not found.')

def method2(path, item, another):
    try:
        client.call(&lt;API endpoint-xyz/read&gt;)
    except InvalidRequest:
        print("Invalid Path! The path {path} was not found.")
    except Forbidden:
        print(f'\nPermission denied! You do not have access tothe path: {path}')
    except InvalidPath:
        print('Error! Failed to update configuration!')


def method3(path, item, another):
    try:
        client.call(&lt;API endpoint/some/other/path/dostuff&gt;)
    except InvalidRequest:
        print("Invalid Path! The path {path} was not found.")
    except UnexpectedError:
        print('Error! cannot generate access tokens.')

For me, this looks repetitive and not pythonic, is there a way to improvise this and avoid calling same expections across functions, and still raise errors and make use of exceptions?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/r1gv4d2
πŸ“…︎ Jan 23 2022
🚨︎ report
Global Exception Handling in .NET 6 enlear.academy/global-exc…
πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/Final_Use_4913
πŸ“…︎ Jan 12 2022
🚨︎ report
Global Exception handling in .Net 6
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Final_Use_4913
πŸ“…︎ Jan 14 2022
🚨︎ report
JIT compilers and exception handling

Hi all,

currently working on a JIT for a virtual machine using Cranelift, which basically helps me not to focus on the backend, but there are few things to consider anyway: exceptions.

At the current state, I'm still designing this virtual machine, it has to emulate a Pentium 3 processor in protected mode, and it's not trivial at all, again Cranelift helps me build functions of this form:

int block_0xDEADBEEF( VMContext *ctx ) { ...body }

Where the result is the exit code of the block, as for C' int main(), it's 0 for success, else it forcefully stops and flow returns to user's code.

Now, a series of exceptions could happen, like a division by zero, invalid memory access and so on, which are host problem too in some cases, and I'd like to share and discuss what I came up to more experienced programmers in this field:

First of all, I don't want any signal handlers routine registered, it's just a pain in the butt to support, so I came up with the idea to call user defined functions ( callbacks ) in such cases:

int exit_code = 0;
/// software interrupt case like int 0x80 or syscall
block_with_interrupt: {
  int callback_result = ctx-&gt;on_software_interrupt(ctx, INTERRUPT_CODE);
  if ( callback_result != 0 ) {
    exit_code = callback_result;
    goto exit;
  }
}
/// memory load: mov eax, [edi]
block_with_load: {
  int   edi = ctx-&gt;cpu.edi;
  // shift right by twelve, the page table is just a giant pointer array to 4096bytes chunks
  int *page = ctx-&gt;mem_pages[edi &gt;&gt; 12];
  if ( page != NULL ) {
    // mask by 4095 and divide by 4, result is the index of such element in an array of 1024 int(s), which are held in a 4096 byte page.
    ctx-&gt;cpu.eax = page[(edi&amp;0xFFF) &gt;&gt; 2]; // non-aligned memory access isn't addressed in this snippet for brevity
  }
  else {  /// ouch, maybe it's MMIO
    int eax;
    int callback_result = ctx-&gt;load32(ctx, edi, &amp;eax);
    if ( callback_result != 0 ) {
      exit_code = callback_result;
      goto exit;
    }
    else {
      ctx-&gt;cpu.eax = eax;
    }
  }
}
exit: {
  return exit_code;
}

these are snippets of a pseudo-representation of the intermediate representation I assemble, and written in such a way to help readability, Cranelift's blocks do have input, so there's no function global variable such as exit_code, but a branch exit(exit_code: i32). The callback's result will then define whether this block of code should continue or forcefully stop. I would enjoy you

... keep reading on reddit ➑

πŸ‘︎ 12
πŸ’¬︎
πŸ‘€︎ u/marco_has_cookies
πŸ“…︎ Dec 15 2021
🚨︎ report
Handling exceptions for class members set by methods?

public static class SomeClass {

public static readonly string APIKEY = GetApiKey();

...

public static string GetApiKey() {

...

}

}

Because APIKEY is a class member, I can't use a try/catch block to handle any exception GetApiKey() throws. How should I do this instead?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/chrisxfire
πŸ“…︎ Dec 07 2021
🚨︎ report
Hooking on Windows via Vectored Exception Handling mark.rxmsolutions.com/hoo…
πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/digicat
πŸ“…︎ Dec 22 2021
🚨︎ report
In Java, Exception handling needs Exception Handling.
πŸ‘︎ 1k
πŸ’¬︎
πŸ‘€︎ u/dj45689
πŸ“…︎ Jul 16 2021
🚨︎ report
Handling MSAL exceptions

Hi all,

I'm not 100% sure what's happening here so I'm probably not going to explain this very well.

I'm trying to handle exceptions for the Connect-ExchangeOnline cmdlet, specifically incorrect username/password combos.

When inputting incorrect creds I seem to be getting 2 exceptions back:

System.ArgumentException (shortened for readability):

Error Acquiring Token:
System.ArgumentException: The user is not recognized as a managed user, or a federated user.Azure AD was not able to identify the IdP that needs to process the user U/P: Wrong username ---&gt; Microsoft.Identity.Client.MsalClientException: Unsupported User Type 'Unknown'. Please see https://aka.ms/msal-net-up. 
   at Microsoft.Identity.Client.Internal.Requests.UsernamePasswordRequest

.....

System.AggregateException:

New-ExoPSSession : One or more errors occurred.
At C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\2.0.5\netFramework\ExchangeOnlineManagement.psm1:475 char:30
+ ... PSSession = New-ExoPSSession -ExchangeEnvironmentName $ExchangeEnviro ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-ExoPSSession], AggregateException
    + FullyQualifiedErrorId : System.AggregateException,Microsoft.Exchange.Management.ExoPowershellSnapin.NewExoPSSession

I don't seem to be able to handle the first exception- it isn't stored in the automatic variable $Error.

I'd really like to handle the first exception because it includes the line "user is not recognized", but I have no idea how to reference it.

After doing some research I landed on this article which explains how to handle MSAL (Microsot Authentication Library) exceptions, but I'm too smooth brain to understand what I need to do.

Can anyone shed some light on handling System.ArgumentException?

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/llovedoggos
πŸ“…︎ Nov 19 2021
🚨︎ report
It's time to learn about asynchronous functions in #SwiftLang using async/await syntax. Let's refactor a code full of closures and complicated error handling! youtu.be/esmf26aGz4s
πŸ‘︎ 15
πŸ’¬︎
πŸ‘€︎ u/pitt500
πŸ“…︎ Jun 29 2021
🚨︎ report
Exception handling - some basics for newbies

In the wild I see a disturbing amount of exception handling which just eats exceptions or catches and throws them back without any processing and it's the most frustrating thing so here's some tips to write your exception handling better if you new to code.

  1. Decide on logging. Serilog is a great bit of logging middleware which you can easily integrate into your apps via nuget/dotnet cli packages.
  2. USE your logging. If you're intent on catching exceptions in your code, at least log them when you do; even if you're not going to handle anything like closing database connections with the exception handling, just make a note somewhere that the exception occurred at all.

Don't just catch and throw

This is one thing that bothers me the most when I inherit a project and read the code; I see a lot of this:

try
{
    // do something
}
catch (Exception ex)
{
    throw;
}

Leaving the code like this, particularly in code that's further away from your UI, is essentially pointless. The only time you would ever do anything like this is when you're also incorporating your finally block into it so that there's some handling that happens here:

try
{
    // do something
}
catch (Exception ex)
{
    throw;
}
finally
{
    // handle some condition like closing the database connection or garbage disposal
}

This way you're still able to tell your user about the exception on the UI, but now you're also addressing other concerns that may need attention aswell.

Don't eat your exceptions

If you're catching an exception, make sure and do something with it. Leaving your catch block empty means that the exception occurs, but code execution doesn't ever stop. This means that values and conditions that may be needed later on probably won't exist or won't be what's expected and then you're just going to end up getting A LOT more exceptions later on and your software will be an absolute disaster.

NEVER leave an empty catch block.

Reporting errors at the top of your stack

Often times, I'll see these empty try...catch blocks right down in a data repository that sits directly on top of the database and while they can be worthwhile if used properly (as above) to log the error and/or handle some other condition, it's usually best to have some catch on the top of the stack - that being in your event handler that triggered the action your code was wor

... keep reading on reddit ➑

πŸ‘︎ 15
πŸ’¬︎
πŸ‘€︎ u/loganhimp
πŸ“…︎ Oct 05 2021
🚨︎ report
Confused about exception handling

Hi everyone! I was learning about exception handling and pretty confused about it. I kind of get the idea but I have a couple questions.

  1. Why do we have to put a try block around code that might throw an exception and a catch block. I feel like this would make the code more messy if we constantly do it.
  2. Why is it best practice to catch by reference? Is it because it is more efficient instead of copying it again.
  3. Why should we throw objects instead of primitive types?

Sorry if these questions are simple.

πŸ‘︎ 14
πŸ’¬︎
πŸ‘€︎ u/SalThePotato
πŸ“…︎ Sep 30 2021
🚨︎ report
Can anyone tell me why my exception would receive an invalid syntax?

Can anyone tell me why my exception would receive an invalid syntax?

import time
from selenium import webdriver
browser = webdriver.Chrome('C:\Users\info\Desktop\GPU_Shopping_Bot\chromedriver')

browser.get("https://www.bestbuy.com/site/nvidia-geforce-rtx-3080-ti-12gb-gddr6x-pci-express-4-0-graphics-card-titanium-and-black/6462956.p?skuId=6462956")





buyButton = False

while not buyButton:
    
    try:
        
        addToCartBtn = addButton = browser.find_element_by_class_name("btn-disabled")
        
        
        print("Button isnt ready yet.")
        
        time.sleep(1)
        browser.refresh()
        
        
        except:
            
            addToCartBtn = addButton = browser.find_element_by_class_name("btn-primary")
            
            
            print("Button was clicked.")
            addToCartBtn.click()
            buyButton = True

Thanks

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/TheMuffinMan2554
πŸ“…︎ Jun 12 2021
🚨︎ report
Forth exception handling write-up niedzejkob.p4.team/bootst…
πŸ‘︎ 18
πŸ’¬︎
πŸ‘€︎ u/rickcarlino
πŸ“…︎ Sep 23 2021
🚨︎ report
errors and exception handling in django.

Hi, I started learning about this topic and I was wondering if there is any simple yet useful case of using errors and exception handling in django? Say in a simple CRUD blog app.

Was wondering how I can incorporate these and almost all the usecase I found are really specific to the project or its mostly used in django REST framework.

Are there any errors and exception handling in django to do in this CRUD blog app case? Something close I've found while doing my own project is using "get object or 404". But not someting like try, except. Is it even neccesary??? <<--

πŸ‘︎ 7
πŸ’¬︎
πŸ“…︎ Oct 23 2021
🚨︎ report
Please don't kill me, but what's the deal with exception-handling?

Literally, if my understanding of exception-handling is that it is completely unnecessary in code? The reason for this is that if you use a catch, the program goes into that function to look for the throw and if it doesn't see it. It terminates. Like what? What is the point of using exception-handling if all I am going to be doing is making the program terminate before I want it to? Do any of you use exception-handling? What's it purpose aside from terminating programs?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Outer_heaven94
πŸ“…︎ Oct 08 2021
🚨︎ report
Which irq, i need to include in idt for exception handling and drivers support.

Hello, i writing microkernel and currently i stucked in irq setup.

As exactly i cannot understood which irq will i need to include in idt except fault handlers;

All drivers in my os will run in userspace.

πŸ‘︎ 12
πŸ’¬︎
πŸ‘€︎ u/Snow_Zigzagut
πŸ“…︎ Sep 26 2021
🚨︎ report

Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.