{"id":1103,"hash":"2d612e84e3c4a9418854fbf6b4af72b915ce33564df296875e050e0eb5a0c4ea","pattern":"Catching boto3 ClientError subclass","full_message":"With code like the snippet below, we can catch AWS exceptions:\n\nfrom aws_utils import make_session\n\nsession = make_session()\ncf = session.resource(\"iam\")\nrole = cf.Role(\"foo\")\ntry:\n    role.load()\nexcept Exception as e:\n    print(type(e))\n    raise e\n\nThe returned error is of type botocore.errorfactory.NoSuchEntityException. However, when I try to import this exception, I get this:\n\n>>> import botocore.errorfactory.NoSuchEntityException\nTraceback (most recent call last):\n  File \"<stdin>\", line 1, in <module>\nImportError: No module named NoSuchEntityException\n\nThe best method I could find of catching this specific error is:\n\nfrom botocore.exceptions import ClientError\nsession = make_session()\ncf = session.resource(\"iam\")\nrole = cf.Role(\"foo\")\ntry:\n    role.load()\nexcept ClientError as e:\n    if e.response[\"Error\"][\"Code\"] == \"NoSuchEntity\":\n        # ignore the target exception\n        pass\n    else:\n        # this is not the exception we are looking for\n        raise e\n\nBut this seems very \"hackish\". Is there a way to directly import and catch specific subclasses of ClientError in boto3?\n\nEDIT: Note that if you catch errors in the second way and print the type, it will be ClientError.","ecosystem":"pypi","package_name":"amazon-web-services","package_version":null,"solution":"If you're using the client you can catch the exceptions like this:\n\nimport boto3\n\ndef exists(role_name):\n    client = boto3.client('iam')\n    try:\n        client.get_role(RoleName='foo')\n        return True\n    except client.exceptions.NoSuchEntityException:\n        return False","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/43354059/catching-boto3-clienterror-subclass","votes":33,"created_at":"2026-04-19T04:52:20.956373+00:00","updated_at":"2026-04-19T04:52:20.956373+00:00"}