Claim Against Exceptions

I read some information about when to use assert and when to use an exception. What I do not understand why?

for example: Statements are intended to be used solely as a means of detecting programming errors as well as errors. On the contrary, an exception may indicate other types of errors or “exceptional” conditions; for example, incorrect user input, missing files, full download, etc.

Now: “Statements are intended to be used solely as a means of detecting programming errors as well as errors.” Now, what is harm, all statements have been replaced by exceptions? Will exceptions do the same?

"The statement is for debugging purposes only, and its trigger state should not occur." -: Now it’s good if I use exceptions, then exceptions, then exceptions will never be thrown

From my understanding, exceptions can all claim except that they cannot be disabled. Does disconnecting disable ONLY the reason why they should be used?

Is there a reason WHY to use them, rather than WHEN to use them?

thanks

+4
source share
7 answers

I see two use cases for claims in production code:

At the beginning of the method, you would normally check if this parameter is valid. For public methods that you would use if statutes and exceptions. For private methods, you must perform simelar checks with assert. The idea is to avoid redundant production checks during testing (or when something goes wrong), you can simply activate the statements to perform a double check.

Another reason for using statements is to document the assumptions that are used in the following code. For example, some value is considered never equal to zero.

Here is a sample code

public class Exampel { public publicMethod(final Integer i) { if (i == null) { throw new RuntimeException("i should not be null"); } privateMethod(i): } private privateMethod(final Integer i) { assert i != null; // do something } } 

You would not want to check for null several times. You just assumed that privateMethod is privateMethod used correctly. You also give anyone reading your code a hint that passing null to privateMethod is the wrong thing.

0
source

Assemblers are used in test cases to make sure that what you created in the future will do something unexpected. You can argue that, for example, exceptions are thrown by false input.

Many times in programming, changing one thing means you need to change other pieces of code. Statements confirm that what you change does not violate the code you wrote earlier.

Exceptions are good. They are expected and processed through exceptions. You have exceptions for incorrect login and password, for example.

You can argue that with an incorrect login or password, the expected exception occurs.

The statement contains three main things. What you are testing (function name, for example, sign_in ), what is included (function parameters, i.e. {'email': ' john@example.com ', 'password': hashlib.md5('my_password')} ) , and what comes out ( assertTrue('user_name' in response, 'Expecting user_name to be in response!') ).

Exceptions are normal, logical alternatives in the code. Statements are tests to make sure logical paths are followed when they should be.

According to the python unittest framework, you can state that exceptions are thrown:

 import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def test_shuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) # should raise an exception for an immutable sequence self.assertRaises(TypeError, random.shuffle, (1,2,3)) def test_choice(self): element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ == '__main__': unittest.main() 
+3
source
Statements

are intended for selective shutdown and by default they are disconnected. You should use them when there are conditions that should never be, but they can be checked if you really need to. Think of them as exceptional exceptions.

Exceptions and their checks are always included. Despite their exclusivity, they can still occur at any time.

Statements can check for coding errors, and after you program without errors, they should not be needed. Exceptions may be thrown due to values ​​that may not be under your control, such as input.

+2
source

Statements in working code, unlike test code, must verify the correctness of the entered code values. If the values ​​are incorrect, a statement exception is thrown.

You can write your own code to check the values ​​and choose an exception of your choice.

Assertions are easy to use and, like logging, can be disabled in production code that has been fully debugged. In addition, anyone who reads the code knows why the test is there without thinking about it. Thus, it saves time. (This will save you time when you come back and read the code you wrote two years ago.)

In any case, it works.

+1
source

Many programmers convert statements into exception checks into release code. Or they can use two different types of statements to convert one, not the others, if some of them are very performance sensitive.

This is part of defensive programming. Statements must document impossible conditions. However, real-life programmers know that sometimes impossible conditions occur due to unverified code paths, errors in system libraries, or hardware errors.

As a rule, there is very little harm in converting statements to exceptions. Some harm that can happen, in Java, it can introduce a new type of exception into a method that previously did not have this. Another harm may be that the converted assert may be inside a loop that requires very high performance, and the assert check may slow it down too much.

+1
source

I think the main difference is that the statements make it possible to see that the problem occurred earlier than the exception. This way, it gives you an earlier point in execution to try to do something (or maybe nothing at all, let it not work). So you would use them if you want to see how the execution is done before something really bad happens (exception thrown).

One dramatic analogy that I can think of is Soyuz launch vehicles on the ISS, sometimes you hear that an automatic rocket went off course at the beginning and immediately caused self-destruction. I would suggest that this is a bit of a statement that they use to determine if the missile heading is correct (if that was the exception, by the time the missile could be thrown, it might have already hit something).

0
source
Statements

are intended for selective shutdown and by default they are disconnected. You should use them when there are conditions that should never be, but they can be checked if you really need to. Think of them as exceptional exceptions.

Exceptions and their checks are always included. Despite their exclusivity, they can still occur at any time.

Statements

detect coding errors. Once your program is free, they will not be needed and can be disabled. Exceptions identify misuse or input and cannot be safely disabled.

0
source

Source: https://habr.com/ru/post/1495825/


All Articles