Showing posts with the label Except

Python - Except and Handling Different Types of Exceptions

Built-in exception types The type of exception we want to handle can be added after except: try :     number = int(input( "Enter a number: " ))     print( "Entered number:" , number) except ValueError:     print( "Conversion failed" ) print( "End program" ) The execpt block in this case only checks for ValueError exceptions, which are thrown when a string to number conversion fails. Python has the following basic exception types: BaseException : the base type for all built-in exceptions Exception : base type used to define custom exception types ArithmeticError : base type for exceptions that relate to arithmetic operations (OverflowError, ZeroDivisionError, FloatingPointError) BufferError : a type of exception that is thrown when a buffer operation cannot be performed LookupError : a type of exception that occurs when you try to access a collection using an index or key that is not valid (e.g. IndexError or KeyError) These classes inherit all t

Try, Except, and Finally - Python Handling Errors and Exceptions

When we write source code in Python, there are two types of errors that we encounter. The first type of error is called syntax errors. Syntax errors occur when you violate the syntax of your programming language. If you have syntax errors in your source code, then you cannot compile your program. When you work in a development environment like Visual Studio Code or PyCharm, etc., the IDE itself can detect syntax errors and show them in some way. The second kind of error is runtime error. Runtime error occurs in a compiled program while it is executing. Runtime errors are also known as Exceptions . For instance, the below script will compile and run successfully because the string "8" can be changed to a number. string = "88" number = int(string) print(number) #Output: 88 Let’s look at another example: string = "python" number = int(string) print(number) Running this script will throw a ValueError exception because the string "python" cannot be co