When to use try/catch blocks?

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them. Don’t catch an exception if you’re only going to log the exception and throw it up the stack. It serves no meaning and clutters code. Do catch an exception when you … Read more

Throwing exceptions in Scala, what is the “official rule”

The basic guideline is to use exceptions for something really exceptional**. For an “ordinary” failure, it’s far better to use Option or Either. If you are interfacing with Java where exceptions are thrown when someone sneezes the wrong way, you can use Try to keep yourself safe. Let’s take some examples. Suppose you have a … Read more

When catch doesn’t actually catch anything [duplicate]

The exception (whatever it was) was caught by catch (Exception e). You didn’t log this exception, so you don’t know what it was. You should log it somehow so you know what really happened. The problem occurs when you return -1. This allows for the possibility of inconsistent ordering, which Java’s current sorting algorithm sometimes … Read more

Is there a way to catch an Exception without having to create a variable?

Starting with PHP 8, it is possible to use a non-capturing catch. This is the relevant RFC, which was voted favourably 48-1. Now it will be possible to do something like this: try { readFile($file); } catch (FileDoesNotExist) { echo “File does not exist”; } catch (UnauthorizedAccess) { echo “User does not have the appropriate … Read more

Java exception not caught

Because some exceptions don’t derive from Exception – e.g. Throwable and Error. Basically the type hierarchy is: Object | Throwable / \ Exception Error Only Throwables and derived classes can be thrown, so if you catch Throwable, that really will catch everything. Throwable, Exception and any exception deriving from Exception other than those derived from … Read more

python try:except:finally

You shouldn’t be writing to the file in the finally block as any exceptions raised there will not be caught by the except block. The except block executes if there is an exception raised by the try block. The finally block always executes whatever happens. Also, there shouldn’t be any need for initializing the file … Read more

Catch KeyError in Python

If it’s raising a KeyError with no message, then it won’t print anything. If you do… try: connection = manager.connect(“I2Cx”) except Exception as e: print repr(e) …you’ll at least get the exception class name. A better alternative is to use multiple except blocks, and only ‘catch’ the exceptions you intend to handle… try: connection = … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)